3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
39 class User
implements IDBAccessObject
{
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH
= 32;
46 * Global constant made accessible as class constants so that autoloader
49 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
52 * @const int Serialized record version.
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE
= 100;
62 * Exclude user options that are set to their default value.
65 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
68 * Array of Strings List of member variables which are saved to the
69 * shared cache (memcached). Any operation which changes the
70 * corresponding database fields must call a cache-clearing function.
73 protected static $mCacheVars = array(
81 'mEmailAuthenticated',
88 // user_properties table
93 * Array of Strings Core rights.
94 * Each of these should have a corresponding message of the form
98 protected static $mCoreRights = array(
127 'editusercssjs', # deprecated
140 'move-categorypages',
141 'move-rootuserpages',
145 'override-export-depth',
168 'userrights-interwiki',
176 * String Cached results of getAllRights()
178 protected static $mAllRights = false;
180 /** Cache variables */
190 /** @var string TS_MW timestamp from the DB */
192 /** @var string TS_MW timestamp from cache */
193 protected $mQuickTouched;
197 public $mEmailAuthenticated;
199 protected $mEmailToken;
201 protected $mEmailTokenExpires;
203 protected $mRegistration;
205 protected $mEditCount;
209 protected $mOptionOverrides;
213 * Bool Whether the cache variables have been loaded.
216 public $mOptionsLoaded;
219 * Array with already loaded items or true if all items have been loaded.
221 protected $mLoadedItems = array();
225 * String Initialization data source if mLoadedItems!==true. May be one of:
226 * - 'defaults' anonymous user initialised from class defaults
227 * - 'name' initialise from mName
228 * - 'id' initialise from mId
229 * - 'session' log in from cookies or session if possible
231 * Use the User::newFrom*() family of functions to set this.
236 * Lazy-initialized variables, invalidated with clearInstanceCache
240 protected $mDatePreference;
248 protected $mBlockreason;
250 protected $mEffectiveGroups;
252 protected $mImplicitGroups;
254 protected $mFormerGroups;
256 protected $mBlockedGlobally;
273 protected $mAllowUsertalk;
276 private $mBlockedFromCreateAccount = false;
279 private $mWatchedItems = array();
281 /** @var integer User::READ_* constant bitfield used to load data */
282 protected $queryFlagsUsed = self
::READ_NORMAL
;
284 public static $idCacheByName = array();
287 * Lightweight constructor for an anonymous user.
288 * Use the User::newFrom* factory functions for other kinds of users.
292 * @see newFromConfirmationCode()
293 * @see newFromSession()
296 public function __construct() {
297 $this->clearInstanceCache( 'defaults' );
303 public function __toString() {
304 return $this->getName();
308 * Load the user table data for this object from the source given by mFrom.
310 * @param integer $flags User::READ_* constant bitfield
312 public function load( $flags = self
::READ_NORMAL
) {
313 if ( $this->mLoadedItems
=== true ) {
317 // Set it now to avoid infinite recursion in accessors
318 $this->mLoadedItems
= true;
319 $this->queryFlagsUsed
= $flags;
321 switch ( $this->mFrom
) {
323 $this->loadDefaults();
326 // Make sure this thread sees its own changes
327 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
328 $flags |
= self
::READ_LATEST
;
329 $this->queryFlagsUsed
= $flags;
332 $this->mId
= self
::idFromName( $this->mName
, $flags );
334 // Nonexistent user placeholder object
335 $this->loadDefaults( $this->mName
);
337 $this->loadFromId( $flags );
341 $this->loadFromId( $flags );
344 if ( !$this->loadFromSession() ) {
345 // Loading from session failed. Load defaults.
346 $this->loadDefaults();
348 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
351 throw new UnexpectedValueException(
352 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
357 * Load user table data, given mId has already been set.
358 * @param integer $flags User::READ_* constant bitfield
359 * @return bool False if the ID does not exist, true otherwise
361 public function loadFromId( $flags = self
::READ_NORMAL
) {
362 if ( $this->mId
== 0 ) {
363 $this->loadDefaults();
367 // Try cache (unless this needs data from the master DB).
368 // NOTE: if this thread called saveSettings(), the cache was cleared.
369 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
370 if ( $latest ||
!$this->loadFromCache() ) {
371 wfDebug( "User: cache miss for user {$this->mId}\n" );
372 // Load from DB (make sure this thread sees its own changes)
373 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
374 $flags |
= self
::READ_LATEST
;
376 if ( !$this->loadFromDatabase( $flags ) ) {
377 // Can't load from ID, user is anonymous
380 $this->saveToCache();
383 $this->mLoadedItems
= true;
384 $this->queryFlagsUsed
= $flags;
391 * @param string $wikiId
392 * @param integer $userId
394 public static function purge( $wikiId, $userId ) {
395 $cache = ObjectCache
::getMainWANInstance();
396 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
401 * @param WANObjectCache $cache
404 protected function getCacheKey( WANObjectCache
$cache ) {
405 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
409 * Load user data from shared cache, given mId has already been set.
411 * @return bool false if the ID does not exist or data is invalid, true otherwise
414 protected function loadFromCache() {
415 if ( $this->mId
== 0 ) {
416 $this->loadDefaults();
420 $cache = ObjectCache
::getMainWANInstance();
421 $data = $cache->get( $this->getCacheKey( $cache ) );
422 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
427 wfDebug( "User: got user {$this->mId} from cache\n" );
429 // Restore from cache
430 foreach ( self
::$mCacheVars as $name ) {
431 $this->$name = $data[$name];
438 * Save user data to the shared cache
440 * This method should not be called outside the User class
442 public function saveToCache() {
445 $this->loadOptions();
447 if ( $this->isAnon() ) {
448 // Anonymous users are uncached
453 foreach ( self
::$mCacheVars as $name ) {
454 $data[$name] = $this->$name;
456 $data['mVersion'] = self
::VERSION
;
457 $opts = Database
::getCacheSetOptions( wfGetDB( DB_SLAVE
) );
459 $cache = ObjectCache
::getMainWANInstance();
460 $key = $this->getCacheKey( $cache );
461 $cache->set( $key, $data, $cache::TTL_HOUR
, $opts );
464 /** @name newFrom*() static factory methods */
468 * Static factory method for creation from username.
470 * This is slightly less efficient than newFromId(), so use newFromId() if
471 * you have both an ID and a name handy.
473 * @param string $name Username, validated by Title::newFromText()
474 * @param string|bool $validate Validate username. Takes the same parameters as
475 * User::getCanonicalName(), except that true is accepted as an alias
476 * for 'valid', for BC.
478 * @return User|bool User object, or false if the username is invalid
479 * (e.g. if it contains illegal characters or is an IP address). If the
480 * username is not present in the database, the result will be a user object
481 * with a name, zero user ID and default settings.
483 public static function newFromName( $name, $validate = 'valid' ) {
484 if ( $validate === true ) {
487 $name = self
::getCanonicalName( $name, $validate );
488 if ( $name === false ) {
491 // Create unloaded user object
495 $u->setItemLoaded( 'name' );
501 * Static factory method for creation from a given user ID.
503 * @param int $id Valid user ID
504 * @return User The corresponding User object
506 public static function newFromId( $id ) {
510 $u->setItemLoaded( 'id' );
515 * Factory method to fetch whichever user has a given email confirmation code.
516 * This code is generated when an account is created or its e-mail address
519 * If the code is invalid or has expired, returns NULL.
521 * @param string $code Confirmation code
522 * @param int $flags User::READ_* bitfield
525 public static function newFromConfirmationCode( $code, $flags = 0 ) {
526 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
527 ?
wfGetDB( DB_MASTER
)
528 : wfGetDB( DB_SLAVE
);
530 $id = $db->selectField(
534 'user_email_token' => md5( $code ),
535 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
539 return $id ? User
::newFromId( $id ) : null;
543 * Create a new user object using data from session or cookies. If the
544 * login credentials are invalid, the result is an anonymous user.
546 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
549 public static function newFromSession( WebRequest
$request = null ) {
551 $user->mFrom
= 'session';
552 $user->mRequest
= $request;
557 * Create a new user object from a user row.
558 * The row should have the following fields from the user table in it:
559 * - either user_name or user_id to load further data if needed (or both)
561 * - all other fields (email, etc.)
562 * It is useless to provide the remaining fields if either user_id,
563 * user_name and user_real_name are not provided because the whole row
564 * will be loaded once more from the database when accessing them.
566 * @param stdClass $row A row from the user table
567 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
570 public static function newFromRow( $row, $data = null ) {
572 $user->loadFromRow( $row, $data );
577 * Static factory method for creation of a "system" user from username.
579 * A "system" user is an account that's used to attribute logged actions
580 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
581 * might include the 'Maintenance script' or 'Conversion script' accounts
582 * used by various scripts in the maintenance/ directory or accounts such
583 * as 'MediaWiki message delivery' used by the MassMessage extension.
585 * This can optionally create the user if it doesn't exist, and "steal" the
586 * account if it does exist.
588 * @param string $name Username
589 * @param array $options Options are:
590 * - validate: As for User::getCanonicalName(), default 'valid'
591 * - create: Whether to create the user if it doesn't already exist, default true
592 * - steal: Whether to reset the account's password and email if it
593 * already exists, default false
596 public static function newSystemUser( $name, $options = array() ) {
598 'validate' => 'valid',
603 $name = self
::getCanonicalName( $name, $options['validate'] );
604 if ( $name === false ) {
608 $dbw = wfGetDB( DB_MASTER
);
609 $row = $dbw->selectRow(
612 self
::selectFields(),
613 array( 'user_password', 'user_newpassword' )
615 array( 'user_name' => $name ),
619 // No user. Create it?
620 return $options['create'] ? self
::createNew( $name ) : null;
622 $user = self
::newFromRow( $row );
624 // A user is considered to exist as a non-system user if it has a
625 // password set, or a temporary password set, or an email set.
626 $passwordFactory = new PasswordFactory();
627 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
629 $password = $passwordFactory->newFromCiphertext( $row->user_password
);
630 } catch ( PasswordError
$e ) {
631 wfDebug( 'Invalid password hash found in database.' );
632 $password = PasswordFactory
::newInvalidPassword();
635 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
636 } catch ( PasswordError
$e ) {
637 wfDebug( 'Invalid password hash found in database.' );
638 $newpassword = PasswordFactory
::newInvalidPassword();
640 if ( !$password instanceof InvalidPassword ||
!$newpassword instanceof InvalidPassword
643 // User exists. Steal it?
644 if ( !$options['steal'] ) {
648 $nopass = PasswordFactory
::newInvalidPassword()->toString();
653 'user_password' => $nopass,
654 'user_newpassword' => $nopass,
655 'user_newpass_time' => null,
657 array( 'user_id' => $user->getId() ),
660 $user->invalidateEmail();
661 $user->saveSettings();
670 * Get the username corresponding to a given user ID
671 * @param int $id User ID
672 * @return string|bool The corresponding username
674 public static function whoIs( $id ) {
675 return UserCache
::singleton()->getProp( $id, 'name' );
679 * Get the real name of a user given their user ID
681 * @param int $id User ID
682 * @return string|bool The corresponding user's real name
684 public static function whoIsReal( $id ) {
685 return UserCache
::singleton()->getProp( $id, 'real_name' );
689 * Get database id given a user name
690 * @param string $name Username
691 * @param integer $flags User::READ_* constant bitfield
692 * @return int|null The corresponding user's ID, or null if user is nonexistent
694 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
695 $nt = Title
::makeTitleSafe( NS_USER
, $name );
696 if ( is_null( $nt ) ) {
701 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
702 return self
::$idCacheByName[$name];
705 $db = ( $flags & self
::READ_LATEST
)
706 ?
wfGetDB( DB_MASTER
)
707 : wfGetDB( DB_SLAVE
);
712 array( 'user_name' => $nt->getText() ),
716 if ( $s === false ) {
719 $result = $s->user_id
;
722 self
::$idCacheByName[$name] = $result;
724 if ( count( self
::$idCacheByName ) > 1000 ) {
725 self
::$idCacheByName = array();
732 * Reset the cache used in idFromName(). For use in tests.
734 public static function resetIdByNameCache() {
735 self
::$idCacheByName = array();
739 * Does the string match an anonymous IPv4 address?
741 * This function exists for username validation, in order to reject
742 * usernames which are similar in form to IP addresses. Strings such
743 * as 300.300.300.300 will return true because it looks like an IP
744 * address, despite not being strictly valid.
746 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
747 * address because the usemod software would "cloak" anonymous IP
748 * addresses like this, if we allowed accounts like this to be created
749 * new users could get the old edits of these anonymous users.
751 * @param string $name Name to match
754 public static function isIP( $name ) {
755 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
756 || IP
::isIPv6( $name );
760 * Is the input a valid username?
762 * Checks if the input is a valid username, we don't want an empty string,
763 * an IP address, anything that contains slashes (would mess up subpages),
764 * is longer than the maximum allowed username size or doesn't begin with
767 * @param string $name Name to match
770 public static function isValidUserName( $name ) {
771 global $wgContLang, $wgMaxNameChars;
774 || User
::isIP( $name )
775 ||
strpos( $name, '/' ) !== false
776 ||
strlen( $name ) > $wgMaxNameChars
777 ||
$name != $wgContLang->ucfirst( $name )
779 wfDebugLog( 'username', __METHOD__
.
780 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
784 // Ensure that the name can't be misresolved as a different title,
785 // such as with extra namespace keys at the start.
786 $parsed = Title
::newFromText( $name );
787 if ( is_null( $parsed )
788 ||
$parsed->getNamespace()
789 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
790 wfDebugLog( 'username', __METHOD__
.
791 ": '$name' invalid due to ambiguous prefixes" );
795 // Check an additional blacklist of troublemaker characters.
796 // Should these be merged into the title char list?
797 $unicodeBlacklist = '/[' .
798 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
799 '\x{00a0}' . # non-breaking space
800 '\x{2000}-\x{200f}' . # various whitespace
801 '\x{2028}-\x{202f}' . # breaks and control chars
802 '\x{3000}' . # ideographic space
803 '\x{e000}-\x{f8ff}' . # private use
805 if ( preg_match( $unicodeBlacklist, $name ) ) {
806 wfDebugLog( 'username', __METHOD__
.
807 ": '$name' invalid due to blacklisted characters" );
815 * Usernames which fail to pass this function will be blocked
816 * from user login and new account registrations, but may be used
817 * internally by batch processes.
819 * If an account already exists in this form, login will be blocked
820 * by a failure to pass this function.
822 * @param string $name Name to match
825 public static function isUsableName( $name ) {
826 global $wgReservedUsernames;
827 // Must be a valid username, obviously ;)
828 if ( !self
::isValidUserName( $name ) ) {
832 static $reservedUsernames = false;
833 if ( !$reservedUsernames ) {
834 $reservedUsernames = $wgReservedUsernames;
835 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
838 // Certain names may be reserved for batch processes.
839 foreach ( $reservedUsernames as $reserved ) {
840 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
841 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
843 if ( $reserved == $name ) {
851 * Usernames which fail to pass this function will be blocked
852 * from new account registrations, but may be used internally
853 * either by batch processes or by user accounts which have
854 * already been created.
856 * Additional blacklisting may be added here rather than in
857 * isValidUserName() to avoid disrupting existing accounts.
859 * @param string $name String to match
862 public static function isCreatableName( $name ) {
863 global $wgInvalidUsernameCharacters;
865 // Ensure that the username isn't longer than 235 bytes, so that
866 // (at least for the builtin skins) user javascript and css files
867 // will work. (bug 23080)
868 if ( strlen( $name ) > 235 ) {
869 wfDebugLog( 'username', __METHOD__
.
870 ": '$name' invalid due to length" );
874 // Preg yells if you try to give it an empty string
875 if ( $wgInvalidUsernameCharacters !== '' ) {
876 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
877 wfDebugLog( 'username', __METHOD__
.
878 ": '$name' invalid due to wgInvalidUsernameCharacters" );
883 return self
::isUsableName( $name );
887 * Is the input a valid password for this user?
889 * @param string $password Desired password
892 public function isValidPassword( $password ) {
893 // simple boolean wrapper for getPasswordValidity
894 return $this->getPasswordValidity( $password ) === true;
898 * Given unvalidated password input, return error message on failure.
900 * @param string $password Desired password
901 * @return bool|string|array True on success, string or array of error message on failure
903 public function getPasswordValidity( $password ) {
904 $result = $this->checkPasswordValidity( $password );
905 if ( $result->isGood() ) {
909 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
910 $messages[] = $error['message'];
912 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
913 $messages[] = $warning['message'];
915 if ( count( $messages ) === 1 ) {
923 * Check if this is a valid password for this user
925 * Create a Status object based on the password's validity.
926 * The Status should be set to fatal if the user should not
927 * be allowed to log in, and should have any errors that
928 * would block changing the password.
930 * If the return value of this is not OK, the password
931 * should not be checked. If the return value is not Good,
932 * the password can be checked, but the user should not be
933 * able to set their password to this.
935 * @param string $password Desired password
936 * @param string $purpose one of 'login', 'create', 'reset'
940 public function checkPasswordValidity( $password, $purpose = 'login' ) {
941 global $wgPasswordPolicy;
943 $upp = new UserPasswordPolicy(
944 $wgPasswordPolicy['policies'],
945 $wgPasswordPolicy['checks']
948 $status = Status
::newGood();
949 $result = false; // init $result to false for the internal checks
951 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
952 $status->error( $result );
956 if ( $result === false ) {
957 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
959 } elseif ( $result === true ) {
962 $status->error( $result );
963 return $status; // the isValidPassword hook set a string $result and returned true
968 * Given unvalidated user input, return a canonical username, or false if
969 * the username is invalid.
970 * @param string $name User input
971 * @param string|bool $validate Type of validation to use:
972 * - false No validation
973 * - 'valid' Valid for batch processes
974 * - 'usable' Valid for batch processes and login
975 * - 'creatable' Valid for batch processes, login and account creation
977 * @throws InvalidArgumentException
978 * @return bool|string
980 public static function getCanonicalName( $name, $validate = 'valid' ) {
981 // Force usernames to capital
983 $name = $wgContLang->ucfirst( $name );
985 # Reject names containing '#'; these will be cleaned up
986 # with title normalisation, but then it's too late to
988 if ( strpos( $name, '#' ) !== false ) {
992 // Clean up name according to title rules,
993 // but only when validation is requested (bug 12654)
994 $t = ( $validate !== false ) ?
995 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
996 // Check for invalid titles
997 if ( is_null( $t ) ) {
1001 // Reject various classes of invalid names
1003 $name = $wgAuth->getCanonicalName( $t->getText() );
1005 switch ( $validate ) {
1009 if ( !User
::isValidUserName( $name ) ) {
1014 if ( !User
::isUsableName( $name ) ) {
1019 if ( !User
::isCreatableName( $name ) ) {
1024 throw new InvalidArgumentException(
1025 'Invalid parameter value for $validate in ' . __METHOD__
);
1031 * Count the number of edits of a user
1033 * @param int $uid User ID to check
1034 * @return int The user's edit count
1036 * @deprecated since 1.21 in favour of User::getEditCount
1038 public static function edits( $uid ) {
1039 wfDeprecated( __METHOD__
, '1.21' );
1040 $user = self
::newFromId( $uid );
1041 return $user->getEditCount();
1045 * Return a random password.
1047 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1048 * @return string New random password
1050 public static function randomPassword() {
1051 global $wgMinimalPasswordLength;
1052 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1056 * Set cached properties to default.
1058 * @note This no longer clears uncached lazy-initialised properties;
1059 * the constructor does that instead.
1061 * @param string|bool $name
1063 public function loadDefaults( $name = false ) {
1065 $this->mName
= $name;
1066 $this->mRealName
= '';
1068 $this->mOptionOverrides
= null;
1069 $this->mOptionsLoaded
= false;
1071 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1072 if ( $loggedOut !== null ) {
1073 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1075 $this->mTouched
= '1'; # Allow any pages to be cached
1078 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1079 $this->mEmailAuthenticated
= null;
1080 $this->mEmailToken
= '';
1081 $this->mEmailTokenExpires
= null;
1082 $this->mRegistration
= wfTimestamp( TS_MW
);
1083 $this->mGroups
= array();
1085 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1089 * Return whether an item has been loaded.
1091 * @param string $item Item to check. Current possibilities:
1095 * @param string $all 'all' to check if the whole object has been loaded
1096 * or any other string to check if only the item is available (e.g.
1100 public function isItemLoaded( $item, $all = 'all' ) {
1101 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1102 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1106 * Set that an item has been loaded
1108 * @param string $item
1110 protected function setItemLoaded( $item ) {
1111 if ( is_array( $this->mLoadedItems
) ) {
1112 $this->mLoadedItems
[$item] = true;
1117 * Load user data from the session or login cookie.
1119 * @return bool True if the user is logged in, false otherwise.
1121 private function loadFromSession() {
1123 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1124 if ( $result !== null ) {
1128 $request = $this->getRequest();
1130 $cookieId = $request->getCookie( 'UserID' );
1131 $sessId = $request->getSessionData( 'wsUserID' );
1133 if ( $cookieId !== null ) {
1134 $sId = intval( $cookieId );
1135 if ( $sessId !== null && $cookieId != $sessId ) {
1136 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1137 cookie user ID ($sId) don't match!" );
1140 $request->setSessionData( 'wsUserID', $sId );
1141 } elseif ( $sessId !== null && $sessId != 0 ) {
1147 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1148 $sName = $request->getSessionData( 'wsUserName' );
1149 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1150 $sName = $request->getCookie( 'UserName' );
1151 $request->setSessionData( 'wsUserName', $sName );
1156 $proposedUser = User
::newFromId( $sId );
1157 if ( !$proposedUser->isLoggedIn() ) {
1162 global $wgBlockDisablesLogin;
1163 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1164 // User blocked and we've disabled blocked user logins
1168 if ( $request->getSessionData( 'wsToken' ) ) {
1170 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1172 } elseif ( $request->getCookie( 'Token' ) ) {
1173 # Get the token from DB/cache and clean it up to remove garbage padding.
1174 # This deals with historical problems with bugs and the default column value.
1175 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1176 // Make comparison in constant time (bug 61346)
1177 $passwordCorrect = strlen( $token )
1178 && hash_equals( $token, $request->getCookie( 'Token' ) );
1181 // No session or persistent login cookie
1185 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1186 $this->loadFromUserObject( $proposedUser );
1187 $request->setSessionData( 'wsToken', $this->mToken
);
1188 wfDebug( "User: logged in from $from\n" );
1191 // Invalid credentials
1192 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1198 * Load user and user_group data from the database.
1199 * $this->mId must be set, this is how the user is identified.
1201 * @param integer $flags User::READ_* constant bitfield
1202 * @return bool True if the user exists, false if the user is anonymous
1204 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1206 $this->mId
= intval( $this->mId
);
1209 if ( !$this->mId
) {
1210 $this->loadDefaults();
1214 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1215 $db = wfGetDB( $index );
1217 $s = $db->selectRow(
1219 self
::selectFields(),
1220 array( 'user_id' => $this->mId
),
1225 $this->queryFlagsUsed
= $flags;
1226 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1228 if ( $s !== false ) {
1229 // Initialise user table data
1230 $this->loadFromRow( $s );
1231 $this->mGroups
= null; // deferred
1232 $this->getEditCount(); // revalidation for nulls
1237 $this->loadDefaults();
1243 * Initialize this object from a row from the user table.
1245 * @param stdClass $row Row from the user table to load.
1246 * @param array $data Further user data to load into the object
1248 * user_groups Array with groups out of the user_groups table
1249 * user_properties Array with properties out of the user_properties table
1251 protected function loadFromRow( $row, $data = null ) {
1254 $this->mGroups
= null; // deferred
1256 if ( isset( $row->user_name
) ) {
1257 $this->mName
= $row->user_name
;
1258 $this->mFrom
= 'name';
1259 $this->setItemLoaded( 'name' );
1264 if ( isset( $row->user_real_name
) ) {
1265 $this->mRealName
= $row->user_real_name
;
1266 $this->setItemLoaded( 'realname' );
1271 if ( isset( $row->user_id
) ) {
1272 $this->mId
= intval( $row->user_id
);
1273 $this->mFrom
= 'id';
1274 $this->setItemLoaded( 'id' );
1279 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1280 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1283 if ( isset( $row->user_editcount
) ) {
1284 $this->mEditCount
= $row->user_editcount
;
1289 if ( isset( $row->user_touched
) ) {
1290 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1295 if ( isset( $row->user_token
) ) {
1296 // The definition for the column is binary(32), so trim the NULs
1297 // that appends. The previous definition was char(32), so trim
1299 $this->mToken
= rtrim( $row->user_token
, " \0" );
1300 if ( $this->mToken
=== '' ) {
1301 $this->mToken
= null;
1307 if ( isset( $row->user_email
) ) {
1308 $this->mEmail
= $row->user_email
;
1309 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1310 $this->mEmailToken
= $row->user_email_token
;
1311 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1312 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1318 $this->mLoadedItems
= true;
1321 if ( is_array( $data ) ) {
1322 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1323 $this->mGroups
= $data['user_groups'];
1325 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1326 $this->loadOptions( $data['user_properties'] );
1332 * Load the data for this user object from another user object.
1336 protected function loadFromUserObject( $user ) {
1338 $user->loadGroups();
1339 $user->loadOptions();
1340 foreach ( self
::$mCacheVars as $var ) {
1341 $this->$var = $user->$var;
1346 * Load the groups from the database if they aren't already loaded.
1348 private function loadGroups() {
1349 if ( is_null( $this->mGroups
) ) {
1350 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1351 ?
wfGetDB( DB_MASTER
)
1352 : wfGetDB( DB_SLAVE
);
1353 $res = $db->select( 'user_groups',
1354 array( 'ug_group' ),
1355 array( 'ug_user' => $this->mId
),
1357 $this->mGroups
= array();
1358 foreach ( $res as $row ) {
1359 $this->mGroups
[] = $row->ug_group
;
1365 * Add the user to the group if he/she meets given criteria.
1367 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1368 * possible to remove manually via Special:UserRights. In such case it
1369 * will not be re-added automatically. The user will also not lose the
1370 * group if they no longer meet the criteria.
1372 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1374 * @return array Array of groups the user has been promoted to.
1376 * @see $wgAutopromoteOnce
1378 public function addAutopromoteOnceGroups( $event ) {
1379 global $wgAutopromoteOnceLogInRC, $wgAuth;
1381 if ( wfReadOnly() ||
!$this->getId() ) {
1385 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1386 if ( !count( $toPromote ) ) {
1390 if ( !$this->checkAndSetTouched() ) {
1391 return array(); // raced out (bug T48834)
1394 $oldGroups = $this->getGroups(); // previous groups
1395 foreach ( $toPromote as $group ) {
1396 $this->addGroup( $group );
1398 // update groups in external authentication database
1399 Hooks
::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1400 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1402 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1404 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1405 $logEntry->setPerformer( $this );
1406 $logEntry->setTarget( $this->getUserPage() );
1407 $logEntry->setParameters( array(
1408 '4::oldgroups' => $oldGroups,
1409 '5::newgroups' => $newGroups,
1411 $logid = $logEntry->insert();
1412 if ( $wgAutopromoteOnceLogInRC ) {
1413 $logEntry->publish( $logid );
1420 * Bump user_touched if it didn't change since this object was loaded
1422 * On success, the mTouched field is updated.
1423 * The user serialization cache is always cleared.
1425 * @return bool Whether user_touched was actually updated
1428 protected function checkAndSetTouched() {
1431 if ( !$this->mId
) {
1432 return false; // anon
1435 // Get a new user_touched that is higher than the old one
1436 $oldTouched = $this->mTouched
;
1437 $newTouched = $this->newTouchedTimestamp();
1439 $dbw = wfGetDB( DB_MASTER
);
1440 $dbw->update( 'user',
1441 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1443 'user_id' => $this->mId
,
1444 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1448 $success = ( $dbw->affectedRows() > 0 );
1451 $this->mTouched
= $newTouched;
1452 $this->clearSharedCache();
1454 // Clears on failure too since that is desired if the cache is stale
1455 $this->clearSharedCache( 'refresh' );
1462 * Clear various cached data stored in this object. The cache of the user table
1463 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1465 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1466 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1468 public function clearInstanceCache( $reloadFrom = false ) {
1469 $this->mNewtalk
= -1;
1470 $this->mDatePreference
= null;
1471 $this->mBlockedby
= -1; # Unset
1472 $this->mHash
= false;
1473 $this->mRights
= null;
1474 $this->mEffectiveGroups
= null;
1475 $this->mImplicitGroups
= null;
1476 $this->mGroups
= null;
1477 $this->mOptions
= null;
1478 $this->mOptionsLoaded
= false;
1479 $this->mEditCount
= null;
1481 if ( $reloadFrom ) {
1482 $this->mLoadedItems
= array();
1483 $this->mFrom
= $reloadFrom;
1488 * Combine the language default options with any site-specific options
1489 * and add the default language variants.
1491 * @return array Array of String options
1493 public static function getDefaultOptions() {
1494 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1496 static $defOpt = null;
1497 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1498 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1499 // mid-request and see that change reflected in the return value of this function.
1500 // Which is insane and would never happen during normal MW operation
1504 $defOpt = $wgDefaultUserOptions;
1505 // Default language setting
1506 $defOpt['language'] = $wgContLang->getCode();
1507 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1508 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1510 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1511 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1513 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1515 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1521 * Get a given default option value.
1523 * @param string $opt Name of option to retrieve
1524 * @return string Default option value
1526 public static function getDefaultOption( $opt ) {
1527 $defOpts = self
::getDefaultOptions();
1528 if ( isset( $defOpts[$opt] ) ) {
1529 return $defOpts[$opt];
1536 * Get blocking information
1537 * @param bool $bFromSlave Whether to check the slave database first.
1538 * To improve performance, non-critical checks are done against slaves.
1539 * Check when actually saving should be done against master.
1541 private function getBlockedStatus( $bFromSlave = true ) {
1542 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1544 if ( -1 != $this->mBlockedby
) {
1548 wfDebug( __METHOD__
. ": checking...\n" );
1550 // Initialize data...
1551 // Otherwise something ends up stomping on $this->mBlockedby when
1552 // things get lazy-loaded later, causing false positive block hits
1553 // due to -1 !== 0. Probably session-related... Nothing should be
1554 // overwriting mBlockedby, surely?
1557 # We only need to worry about passing the IP address to the Block generator if the
1558 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1559 # know which IP address they're actually coming from
1560 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1561 $ip = $this->getRequest()->getIP();
1567 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1570 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1572 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1574 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1575 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1576 $block->setTarget( $ip );
1577 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1579 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1580 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1581 $block->setTarget( $ip );
1585 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1586 if ( !$block instanceof Block
1587 && $wgApplyIpBlocksToXff
1589 && !in_array( $ip, $wgProxyWhitelist )
1591 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1592 $xff = array_map( 'trim', explode( ',', $xff ) );
1593 $xff = array_diff( $xff, array( $ip ) );
1594 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1595 $block = Block
::chooseBlock( $xffblocks, $xff );
1596 if ( $block instanceof Block
) {
1597 # Mangle the reason to alert the user that the block
1598 # originated from matching the X-Forwarded-For header.
1599 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1603 if ( $block instanceof Block
) {
1604 wfDebug( __METHOD__
. ": Found block.\n" );
1605 $this->mBlock
= $block;
1606 $this->mBlockedby
= $block->getByName();
1607 $this->mBlockreason
= $block->mReason
;
1608 $this->mHideName
= $block->mHideName
;
1609 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1611 $this->mBlockedby
= '';
1612 $this->mHideName
= 0;
1613 $this->mAllowUsertalk
= false;
1617 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1622 * Whether the given IP is in a DNS blacklist.
1624 * @param string $ip IP to check
1625 * @param bool $checkWhitelist Whether to check the whitelist first
1626 * @return bool True if blacklisted.
1628 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1629 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1631 if ( !$wgEnableDnsBlacklist ) {
1635 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1639 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1643 * Whether the given IP is in a given DNS blacklist.
1645 * @param string $ip IP to check
1646 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1647 * @return bool True if blacklisted.
1649 public function inDnsBlacklist( $ip, $bases ) {
1652 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1653 if ( IP
::isIPv4( $ip ) ) {
1654 // Reverse IP, bug 21255
1655 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1657 foreach ( (array)$bases as $base ) {
1659 // If we have an access key, use that too (ProjectHoneypot, etc.)
1661 if ( is_array( $base ) ) {
1662 if ( count( $base ) >= 2 ) {
1663 // Access key is 1, base URL is 0
1664 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1666 $host = "$ipReversed.{$base[0]}";
1668 $basename = $base[0];
1670 $host = "$ipReversed.$base";
1674 $ipList = gethostbynamel( $host );
1677 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1681 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1690 * Check if an IP address is in the local proxy list
1696 public static function isLocallyBlockedProxy( $ip ) {
1697 global $wgProxyList;
1699 if ( !$wgProxyList ) {
1703 if ( !is_array( $wgProxyList ) ) {
1704 // Load from the specified file
1705 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1708 if ( !is_array( $wgProxyList ) ) {
1710 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1712 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1713 // Old-style flipped proxy list
1722 * Is this user subject to rate limiting?
1724 * @return bool True if rate limited
1726 public function isPingLimitable() {
1727 global $wgRateLimitsExcludedIPs;
1728 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1729 // No other good way currently to disable rate limits
1730 // for specific IPs. :P
1731 // But this is a crappy hack and should die.
1734 return !$this->isAllowed( 'noratelimit' );
1738 * Primitive rate limits: enforce maximum actions per time period
1739 * to put a brake on flooding.
1741 * The method generates both a generic profiling point and a per action one
1742 * (suffix being "-$action".
1744 * @note When using a shared cache like memcached, IP-address
1745 * last-hit counters will be shared across wikis.
1747 * @param string $action Action to enforce; 'edit' if unspecified
1748 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1749 * @return bool True if a rate limiter was tripped
1751 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1752 // Call the 'PingLimiter' hook
1754 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1758 global $wgRateLimits;
1759 if ( !isset( $wgRateLimits[$action] ) ) {
1763 // Some groups shouldn't trigger the ping limiter, ever
1764 if ( !$this->isPingLimitable() ) {
1768 $limits = $wgRateLimits[$action];
1770 $id = $this->getId();
1773 if ( isset( $limits['anon'] ) && $id == 0 ) {
1774 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1777 if ( isset( $limits['user'] ) && $id != 0 ) {
1778 $userLimit = $limits['user'];
1780 if ( $this->isNewbie() ) {
1781 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1782 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1784 if ( isset( $limits['ip'] ) ) {
1785 $ip = $this->getRequest()->getIP();
1786 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1788 if ( isset( $limits['subnet'] ) ) {
1789 $ip = $this->getRequest()->getIP();
1792 if ( IP
::isIPv6( $ip ) ) {
1793 $parts = IP
::parseRange( "$ip/64" );
1794 $subnet = $parts[0];
1795 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1797 $subnet = $matches[1];
1799 if ( $subnet !== false ) {
1800 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1804 // Check for group-specific permissions
1805 // If more than one group applies, use the group with the highest limit
1806 foreach ( $this->getGroups() as $group ) {
1807 if ( isset( $limits[$group] ) ) {
1808 if ( $userLimit === false
1809 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1811 $userLimit = $limits[$group];
1815 // Set the user limit key
1816 if ( $userLimit !== false ) {
1817 list( $max, $period ) = $userLimit;
1818 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1819 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1822 $cache = ObjectCache
::getLocalClusterInstance();
1825 foreach ( $keys as $key => $limit ) {
1826 list( $max, $period ) = $limit;
1827 $summary = "(limit $max in {$period}s)";
1828 $count = $cache->get( $key );
1831 if ( $count >= $max ) {
1832 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1833 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1836 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1839 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1840 if ( $incrBy > 0 ) {
1841 $cache->add( $key, 0, intval( $period ) ); // first ping
1844 if ( $incrBy > 0 ) {
1845 $cache->incr( $key, $incrBy );
1853 * Check if user is blocked
1855 * @param bool $bFromSlave Whether to check the slave database instead of
1856 * the master. Hacked from false due to horrible probs on site.
1857 * @return bool True if blocked, false otherwise
1859 public function isBlocked( $bFromSlave = true ) {
1860 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1864 * Get the block affecting the user, or null if the user is not blocked
1866 * @param bool $bFromSlave Whether to check the slave database instead of the master
1867 * @return Block|null
1869 public function getBlock( $bFromSlave = true ) {
1870 $this->getBlockedStatus( $bFromSlave );
1871 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1875 * Check if user is blocked from editing a particular article
1877 * @param Title $title Title to check
1878 * @param bool $bFromSlave Whether to check the slave database instead of the master
1881 public function isBlockedFrom( $title, $bFromSlave = false ) {
1882 global $wgBlockAllowsUTEdit;
1884 $blocked = $this->isBlocked( $bFromSlave );
1885 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1886 // If a user's name is suppressed, they cannot make edits anywhere
1887 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1888 && $title->getNamespace() == NS_USER_TALK
) {
1890 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1893 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1899 * If user is blocked, return the name of the user who placed the block
1900 * @return string Name of blocker
1902 public function blockedBy() {
1903 $this->getBlockedStatus();
1904 return $this->mBlockedby
;
1908 * If user is blocked, return the specified reason for the block
1909 * @return string Blocking reason
1911 public function blockedFor() {
1912 $this->getBlockedStatus();
1913 return $this->mBlockreason
;
1917 * If user is blocked, return the ID for the block
1918 * @return int Block ID
1920 public function getBlockId() {
1921 $this->getBlockedStatus();
1922 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1926 * Check if user is blocked on all wikis.
1927 * Do not use for actual edit permission checks!
1928 * This is intended for quick UI checks.
1930 * @param string $ip IP address, uses current client if none given
1931 * @return bool True if blocked, false otherwise
1933 public function isBlockedGlobally( $ip = '' ) {
1934 if ( $this->mBlockedGlobally
!== null ) {
1935 return $this->mBlockedGlobally
;
1937 // User is already an IP?
1938 if ( IP
::isIPAddress( $this->getName() ) ) {
1939 $ip = $this->getName();
1941 $ip = $this->getRequest()->getIP();
1944 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1945 $this->mBlockedGlobally
= (bool)$blocked;
1946 return $this->mBlockedGlobally
;
1950 * Check if user account is locked
1952 * @return bool True if locked, false otherwise
1954 public function isLocked() {
1955 if ( $this->mLocked
!== null ) {
1956 return $this->mLocked
;
1959 $authUser = $wgAuth->getUserInstance( $this );
1960 $this->mLocked
= (bool)$authUser->isLocked();
1961 Hooks
::run( 'UserIsLocked', array( $this, &$this->mLocked
) );
1962 return $this->mLocked
;
1966 * Check if user account is hidden
1968 * @return bool True if hidden, false otherwise
1970 public function isHidden() {
1971 if ( $this->mHideName
!== null ) {
1972 return $this->mHideName
;
1974 $this->getBlockedStatus();
1975 if ( !$this->mHideName
) {
1977 $authUser = $wgAuth->getUserInstance( $this );
1978 $this->mHideName
= (bool)$authUser->isHidden();
1979 Hooks
::run( 'UserIsHidden', array( $this, &$this->mHideName
) );
1981 return $this->mHideName
;
1985 * Get the user's ID.
1986 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1988 public function getId() {
1989 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1990 // Special case, we know the user is anonymous
1992 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1993 // Don't load if this was initialized from an ID
2000 * Set the user and reload all fields according to a given ID
2001 * @param int $v User ID to reload
2003 public function setId( $v ) {
2005 $this->clearInstanceCache( 'id' );
2009 * Get the user name, or the IP of an anonymous user
2010 * @return string User's name or IP address
2012 public function getName() {
2013 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2014 // Special case optimisation
2015 return $this->mName
;
2018 if ( $this->mName
=== false ) {
2020 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2022 return $this->mName
;
2027 * Set the user name.
2029 * This does not reload fields from the database according to the given
2030 * name. Rather, it is used to create a temporary "nonexistent user" for
2031 * later addition to the database. It can also be used to set the IP
2032 * address for an anonymous user to something other than the current
2035 * @note User::newFromName() has roughly the same function, when the named user
2037 * @param string $str New user name to set
2039 public function setName( $str ) {
2041 $this->mName
= $str;
2045 * Get the user's name escaped by underscores.
2046 * @return string Username escaped by underscores.
2048 public function getTitleKey() {
2049 return str_replace( ' ', '_', $this->getName() );
2053 * Check if the user has new messages.
2054 * @return bool True if the user has new messages
2056 public function getNewtalk() {
2059 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2060 if ( $this->mNewtalk
=== -1 ) {
2061 $this->mNewtalk
= false; # reset talk page status
2063 // Check memcached separately for anons, who have no
2064 // entire User object stored in there.
2065 if ( !$this->mId
) {
2066 global $wgDisableAnonTalk;
2067 if ( $wgDisableAnonTalk ) {
2068 // Anon newtalk disabled by configuration.
2069 $this->mNewtalk
= false;
2071 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2074 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2078 return (bool)$this->mNewtalk
;
2082 * Return the data needed to construct links for new talk page message
2083 * alerts. If there are new messages, this will return an associative array
2084 * with the following data:
2085 * wiki: The database name of the wiki
2086 * link: Root-relative link to the user's talk page
2087 * rev: The last talk page revision that the user has seen or null. This
2088 * is useful for building diff links.
2089 * If there are no new messages, it returns an empty array.
2090 * @note This function was designed to accomodate multiple talk pages, but
2091 * currently only returns a single link and revision.
2094 public function getNewMessageLinks() {
2096 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2098 } elseif ( !$this->getNewtalk() ) {
2101 $utp = $this->getTalkPage();
2102 $dbr = wfGetDB( DB_SLAVE
);
2103 // Get the "last viewed rev" timestamp from the oldest message notification
2104 $timestamp = $dbr->selectField( 'user_newtalk',
2105 'MIN(user_last_timestamp)',
2106 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2108 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2109 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2113 * Get the revision ID for the last talk page revision viewed by the talk
2115 * @return int|null Revision ID or null
2117 public function getNewMessageRevisionId() {
2118 $newMessageRevisionId = null;
2119 $newMessageLinks = $this->getNewMessageLinks();
2120 if ( $newMessageLinks ) {
2121 // Note: getNewMessageLinks() never returns more than a single link
2122 // and it is always for the same wiki, but we double-check here in
2123 // case that changes some time in the future.
2124 if ( count( $newMessageLinks ) === 1
2125 && $newMessageLinks[0]['wiki'] === wfWikiID()
2126 && $newMessageLinks[0]['rev']
2128 /** @var Revision $newMessageRevision */
2129 $newMessageRevision = $newMessageLinks[0]['rev'];
2130 $newMessageRevisionId = $newMessageRevision->getId();
2133 return $newMessageRevisionId;
2137 * Internal uncached check for new messages
2140 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2141 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2142 * @return bool True if the user has new messages
2144 protected function checkNewtalk( $field, $id ) {
2145 $dbr = wfGetDB( DB_SLAVE
);
2147 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__
);
2149 return $ok !== false;
2153 * Add or update the new messages flag
2154 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2155 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2156 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2157 * @return bool True if successful, false otherwise
2159 protected function updateNewtalk( $field, $id, $curRev = null ) {
2160 // Get timestamp of the talk page revision prior to the current one
2161 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2162 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2163 // Mark the user as having new messages since this revision
2164 $dbw = wfGetDB( DB_MASTER
);
2165 $dbw->insert( 'user_newtalk',
2166 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2169 if ( $dbw->affectedRows() ) {
2170 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2173 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2179 * Clear the new messages flag for the given user
2180 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2181 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2182 * @return bool True if successful, false otherwise
2184 protected function deleteNewtalk( $field, $id ) {
2185 $dbw = wfGetDB( DB_MASTER
);
2186 $dbw->delete( 'user_newtalk',
2187 array( $field => $id ),
2189 if ( $dbw->affectedRows() ) {
2190 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2193 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2199 * Update the 'You have new messages!' status.
2200 * @param bool $val Whether the user has new messages
2201 * @param Revision $curRev New, as yet unseen revision of the user talk
2202 * page. Ignored if null or !$val.
2204 public function setNewtalk( $val, $curRev = null ) {
2205 if ( wfReadOnly() ) {
2210 $this->mNewtalk
= $val;
2212 if ( $this->isAnon() ) {
2214 $id = $this->getName();
2217 $id = $this->getId();
2221 $changed = $this->updateNewtalk( $field, $id, $curRev );
2223 $changed = $this->deleteNewtalk( $field, $id );
2227 $this->invalidateCache();
2232 * Generate a current or new-future timestamp to be stored in the
2233 * user_touched field when we update things.
2234 * @return string Timestamp in TS_MW format
2236 private function newTouchedTimestamp() {
2237 global $wgClockSkewFudge;
2239 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2240 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2241 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2248 * Clear user data from memcached
2250 * Use after applying updates to the database; caller's
2251 * responsibility to update user_touched if appropriate.
2253 * Called implicitly from invalidateCache() and saveSettings().
2255 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2257 public function clearSharedCache( $mode = 'changed' ) {
2258 if ( !$this->getId() ) {
2262 $cache = ObjectCache
::getMainWANInstance();
2263 $key = $this->getCacheKey( $cache );
2264 if ( $mode === 'refresh' ) {
2265 $cache->delete( $key, 1 );
2267 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2268 $cache->delete( $key );
2274 * Immediately touch the user data cache for this account
2276 * Calls touch() and removes account data from memcached
2278 public function invalidateCache() {
2280 $this->clearSharedCache();
2284 * Update the "touched" timestamp for the user
2286 * This is useful on various login/logout events when making sure that
2287 * a browser or proxy that has multiple tenants does not suffer cache
2288 * pollution where the new user sees the old users content. The value
2289 * of getTouched() is checked when determining 304 vs 200 responses.
2290 * Unlike invalidateCache(), this preserves the User object cache and
2291 * avoids database writes.
2295 public function touch() {
2296 $id = $this->getId();
2298 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2299 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2300 $this->mQuickTouched
= null;
2305 * Validate the cache for this account.
2306 * @param string $timestamp A timestamp in TS_MW format
2309 public function validateCache( $timestamp ) {
2310 return ( $timestamp >= $this->getTouched() );
2314 * Get the user touched timestamp
2316 * Use this value only to validate caches via inequalities
2317 * such as in the case of HTTP If-Modified-Since response logic
2319 * @return string TS_MW Timestamp
2321 public function getTouched() {
2325 if ( $this->mQuickTouched
=== null ) {
2326 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2327 $cache = ObjectCache
::getMainWANInstance();
2329 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2332 return max( $this->mTouched
, $this->mQuickTouched
);
2335 return $this->mTouched
;
2339 * Get the user_touched timestamp field (time of last DB updates)
2340 * @return string TS_MW Timestamp
2343 public function getDBTouched() {
2346 return $this->mTouched
;
2350 * @deprecated Removed in 1.27.
2354 public function getPassword() {
2355 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2359 * @deprecated Removed in 1.27.
2363 public function getTemporaryPassword() {
2364 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2368 * Set the password and reset the random token.
2369 * Calls through to authentication plugin if necessary;
2370 * will have no effect if the auth plugin refuses to
2371 * pass the change through or if the legal password
2374 * As a special case, setting the password to null
2375 * wipes it, so the account cannot be logged in until
2376 * a new password is set, for instance via e-mail.
2378 * @deprecated since 1.27. AuthManager is coming.
2379 * @param string $str New password to set
2380 * @throws PasswordError On failure
2383 public function setPassword( $str ) {
2386 if ( $str !== null ) {
2387 if ( !$wgAuth->allowPasswordChange() ) {
2388 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2391 $status = $this->checkPasswordValidity( $str );
2392 if ( !$status->isGood() ) {
2393 throw new PasswordError( $status->getMessage()->text() );
2397 if ( !$wgAuth->setPassword( $this, $str ) ) {
2398 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2402 $this->setOption( 'watchlisttoken', false );
2403 $this->setPasswordInternal( $str );
2409 * Set the password and reset the random token unconditionally.
2411 * @deprecated since 1.27. AuthManager is coming.
2412 * @param string|null $str New password to set or null to set an invalid
2413 * password hash meaning that the user will not be able to log in
2414 * through the web interface.
2416 public function setInternalPassword( $str ) {
2419 if ( $wgAuth->allowSetLocalPassword() ) {
2421 $this->setOption( 'watchlisttoken', false );
2422 $this->setPasswordInternal( $str );
2427 * Actually set the password and such
2428 * @since 1.27 cannot set a password for a user not in the database
2429 * @param string|null $str New password to set or null to set an invalid
2430 * password hash meaning that the user will not be able to log in
2431 * through the web interface.
2433 private function setPasswordInternal( $str ) {
2434 $id = self
::idFromName( $this->getName(), self
::READ_LATEST
);
2436 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2439 $passwordFactory = new PasswordFactory();
2440 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2441 $dbw = wfGetDB( DB_MASTER
);
2445 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2446 'user_newpassword' => PasswordFactory
::newInvalidPassword()->toString(),
2447 'user_newpass_time' => $dbw->timestampOrNull( null ),
2457 * Get the user's current token.
2458 * @param bool $forceCreation Force the generation of a new token if the
2459 * user doesn't have one (default=true for backwards compatibility).
2460 * @return string Token
2462 public function getToken( $forceCreation = true ) {
2464 if ( !$this->mToken
&& $forceCreation ) {
2467 return $this->mToken
;
2471 * Set the random token (used for persistent authentication)
2472 * Called from loadDefaults() among other places.
2474 * @param string|bool $token If specified, set the token to this value
2476 public function setToken( $token = false ) {
2479 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2481 $this->mToken
= $token;
2486 * Set the password for a password reminder or new account email
2488 * @deprecated since 1.27, AuthManager is coming
2489 * @param string $str New password to set or null to set an invalid
2490 * password hash meaning that the user will not be able to use it
2491 * @param bool $throttle If true, reset the throttle timestamp to the present
2493 public function setNewpassword( $str, $throttle = true ) {
2494 $id = $this->getId();
2496 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2499 $dbw = wfGetDB( DB_MASTER
);
2501 $passwordFactory = new PasswordFactory();
2502 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
2504 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2507 if ( $str === null ) {
2508 $update['user_newpass_time'] = null;
2509 } elseif ( $throttle ) {
2510 $update['user_newpass_time'] = $dbw->timestamp();
2513 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__
);
2517 * Has password reminder email been sent within the last
2518 * $wgPasswordReminderResendTime hours?
2521 public function isPasswordReminderThrottled() {
2522 global $wgPasswordReminderResendTime;
2524 if ( !$wgPasswordReminderResendTime ) {
2530 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
2531 ?
wfGetDB( DB_MASTER
)
2532 : wfGetDB( DB_SLAVE
);
2533 $newpassTime = $db->selectField(
2535 'user_newpass_time',
2536 array( 'user_id' => $this->getId() ),
2540 if ( $newpassTime === null ) {
2543 $expiry = wfTimestamp( TS_UNIX
, $newpassTime ) +
$wgPasswordReminderResendTime * 3600;
2544 return time() < $expiry;
2548 * Get the user's e-mail address
2549 * @return string User's email address
2551 public function getEmail() {
2553 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2554 return $this->mEmail
;
2558 * Get the timestamp of the user's e-mail authentication
2559 * @return string TS_MW timestamp
2561 public function getEmailAuthenticationTimestamp() {
2563 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2564 return $this->mEmailAuthenticated
;
2568 * Set the user's e-mail address
2569 * @param string $str New e-mail address
2571 public function setEmail( $str ) {
2573 if ( $str == $this->mEmail
) {
2576 $this->invalidateEmail();
2577 $this->mEmail
= $str;
2578 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2582 * Set the user's e-mail address and a confirmation mail if needed.
2585 * @param string $str New e-mail address
2588 public function setEmailWithConfirmation( $str ) {
2589 global $wgEnableEmail, $wgEmailAuthentication;
2591 if ( !$wgEnableEmail ) {
2592 return Status
::newFatal( 'emaildisabled' );
2595 $oldaddr = $this->getEmail();
2596 if ( $str === $oldaddr ) {
2597 return Status
::newGood( true );
2600 $this->setEmail( $str );
2602 if ( $str !== '' && $wgEmailAuthentication ) {
2603 // Send a confirmation request to the new address if needed
2604 $type = $oldaddr != '' ?
'changed' : 'set';
2605 $result = $this->sendConfirmationMail( $type );
2606 if ( $result->isGood() ) {
2607 // Say to the caller that a confirmation mail has been sent
2608 $result->value
= 'eauth';
2611 $result = Status
::newGood( true );
2618 * Get the user's real name
2619 * @return string User's real name
2621 public function getRealName() {
2622 if ( !$this->isItemLoaded( 'realname' ) ) {
2626 return $this->mRealName
;
2630 * Set the user's real name
2631 * @param string $str New real name
2633 public function setRealName( $str ) {
2635 $this->mRealName
= $str;
2639 * Get the user's current setting for a given option.
2641 * @param string $oname The option to check
2642 * @param string $defaultOverride A default value returned if the option does not exist
2643 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2644 * @return string User's current value for the option
2645 * @see getBoolOption()
2646 * @see getIntOption()
2648 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2649 global $wgHiddenPrefs;
2650 $this->loadOptions();
2652 # We want 'disabled' preferences to always behave as the default value for
2653 # users, even if they have set the option explicitly in their settings (ie they
2654 # set it, and then it was disabled removing their ability to change it). But
2655 # we don't want to erase the preferences in the database in case the preference
2656 # is re-enabled again. So don't touch $mOptions, just override the returned value
2657 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2658 return self
::getDefaultOption( $oname );
2661 if ( array_key_exists( $oname, $this->mOptions
) ) {
2662 return $this->mOptions
[$oname];
2664 return $defaultOverride;
2669 * Get all user's options
2671 * @param int $flags Bitwise combination of:
2672 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2673 * to the default value. (Since 1.25)
2676 public function getOptions( $flags = 0 ) {
2677 global $wgHiddenPrefs;
2678 $this->loadOptions();
2679 $options = $this->mOptions
;
2681 # We want 'disabled' preferences to always behave as the default value for
2682 # users, even if they have set the option explicitly in their settings (ie they
2683 # set it, and then it was disabled removing their ability to change it). But
2684 # we don't want to erase the preferences in the database in case the preference
2685 # is re-enabled again. So don't touch $mOptions, just override the returned value
2686 foreach ( $wgHiddenPrefs as $pref ) {
2687 $default = self
::getDefaultOption( $pref );
2688 if ( $default !== null ) {
2689 $options[$pref] = $default;
2693 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2694 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2701 * Get the user's current setting for a given option, as a boolean value.
2703 * @param string $oname The option to check
2704 * @return bool User's current value for the option
2707 public function getBoolOption( $oname ) {
2708 return (bool)$this->getOption( $oname );
2712 * Get the user's current setting for a given option, as an integer value.
2714 * @param string $oname The option to check
2715 * @param int $defaultOverride A default value returned if the option does not exist
2716 * @return int User's current value for the option
2719 public function getIntOption( $oname, $defaultOverride = 0 ) {
2720 $val = $this->getOption( $oname );
2722 $val = $defaultOverride;
2724 return intval( $val );
2728 * Set the given option for a user.
2730 * You need to call saveSettings() to actually write to the database.
2732 * @param string $oname The option to set
2733 * @param mixed $val New value to set
2735 public function setOption( $oname, $val ) {
2736 $this->loadOptions();
2738 // Explicitly NULL values should refer to defaults
2739 if ( is_null( $val ) ) {
2740 $val = self
::getDefaultOption( $oname );
2743 $this->mOptions
[$oname] = $val;
2747 * Get a token stored in the preferences (like the watchlist one),
2748 * resetting it if it's empty (and saving changes).
2750 * @param string $oname The option name to retrieve the token from
2751 * @return string|bool User's current value for the option, or false if this option is disabled.
2752 * @see resetTokenFromOption()
2754 * @deprecated 1.26 Applications should use the OAuth extension
2756 public function getTokenFromOption( $oname ) {
2757 global $wgHiddenPrefs;
2759 $id = $this->getId();
2760 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2764 $token = $this->getOption( $oname );
2766 // Default to a value based on the user token to avoid space
2767 // wasted on storing tokens for all users. When this option
2768 // is set manually by the user, only then is it stored.
2769 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2776 * Reset a token stored in the preferences (like the watchlist one).
2777 * *Does not* save user's preferences (similarly to setOption()).
2779 * @param string $oname The option name to reset the token in
2780 * @return string|bool New token value, or false if this option is disabled.
2781 * @see getTokenFromOption()
2784 public function resetTokenFromOption( $oname ) {
2785 global $wgHiddenPrefs;
2786 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2790 $token = MWCryptRand
::generateHex( 40 );
2791 $this->setOption( $oname, $token );
2796 * Return a list of the types of user options currently returned by
2797 * User::getOptionKinds().
2799 * Currently, the option kinds are:
2800 * - 'registered' - preferences which are registered in core MediaWiki or
2801 * by extensions using the UserGetDefaultOptions hook.
2802 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2803 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2804 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2805 * be used by user scripts.
2806 * - 'special' - "preferences" that are not accessible via User::getOptions
2807 * or User::setOptions.
2808 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2809 * These are usually legacy options, removed in newer versions.
2811 * The API (and possibly others) use this function to determine the possible
2812 * option types for validation purposes, so make sure to update this when a
2813 * new option kind is added.
2815 * @see User::getOptionKinds
2816 * @return array Option kinds
2818 public static function listOptionKinds() {
2821 'registered-multiselect',
2822 'registered-checkmatrix',
2830 * Return an associative array mapping preferences keys to the kind of a preference they're
2831 * used for. Different kinds are handled differently when setting or reading preferences.
2833 * See User::listOptionKinds for the list of valid option types that can be provided.
2835 * @see User::listOptionKinds
2836 * @param IContextSource $context
2837 * @param array $options Assoc. array with options keys to check as keys.
2838 * Defaults to $this->mOptions.
2839 * @return array The key => kind mapping data
2841 public function getOptionKinds( IContextSource
$context, $options = null ) {
2842 $this->loadOptions();
2843 if ( $options === null ) {
2844 $options = $this->mOptions
;
2847 $prefs = Preferences
::getPreferences( $this, $context );
2850 // Pull out the "special" options, so they don't get converted as
2851 // multiselect or checkmatrix.
2852 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2853 foreach ( $specialOptions as $name => $value ) {
2854 unset( $prefs[$name] );
2857 // Multiselect and checkmatrix options are stored in the database with
2858 // one key per option, each having a boolean value. Extract those keys.
2859 $multiselectOptions = array();
2860 foreach ( $prefs as $name => $info ) {
2861 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2862 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2863 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2864 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2866 foreach ( $opts as $value ) {
2867 $multiselectOptions["$prefix$value"] = true;
2870 unset( $prefs[$name] );
2873 $checkmatrixOptions = array();
2874 foreach ( $prefs as $name => $info ) {
2875 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2876 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2877 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2878 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2879 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2881 foreach ( $columns as $column ) {
2882 foreach ( $rows as $row ) {
2883 $checkmatrixOptions["$prefix$column-$row"] = true;
2887 unset( $prefs[$name] );
2891 // $value is ignored
2892 foreach ( $options as $key => $value ) {
2893 if ( isset( $prefs[$key] ) ) {
2894 $mapping[$key] = 'registered';
2895 } elseif ( isset( $multiselectOptions[$key] ) ) {
2896 $mapping[$key] = 'registered-multiselect';
2897 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2898 $mapping[$key] = 'registered-checkmatrix';
2899 } elseif ( isset( $specialOptions[$key] ) ) {
2900 $mapping[$key] = 'special';
2901 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2902 $mapping[$key] = 'userjs';
2904 $mapping[$key] = 'unused';
2912 * Reset certain (or all) options to the site defaults
2914 * The optional parameter determines which kinds of preferences will be reset.
2915 * Supported values are everything that can be reported by getOptionKinds()
2916 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2918 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2919 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2920 * for backwards-compatibility.
2921 * @param IContextSource|null $context Context source used when $resetKinds
2922 * does not contain 'all', passed to getOptionKinds().
2923 * Defaults to RequestContext::getMain() when null.
2925 public function resetOptions(
2926 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2927 IContextSource
$context = null
2930 $defaultOptions = self
::getDefaultOptions();
2932 if ( !is_array( $resetKinds ) ) {
2933 $resetKinds = array( $resetKinds );
2936 if ( in_array( 'all', $resetKinds ) ) {
2937 $newOptions = $defaultOptions;
2939 if ( $context === null ) {
2940 $context = RequestContext
::getMain();
2943 $optionKinds = $this->getOptionKinds( $context );
2944 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2945 $newOptions = array();
2947 // Use default values for the options that should be deleted, and
2948 // copy old values for the ones that shouldn't.
2949 foreach ( $this->mOptions
as $key => $value ) {
2950 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2951 if ( array_key_exists( $key, $defaultOptions ) ) {
2952 $newOptions[$key] = $defaultOptions[$key];
2955 $newOptions[$key] = $value;
2960 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2962 $this->mOptions
= $newOptions;
2963 $this->mOptionsLoaded
= true;
2967 * Get the user's preferred date format.
2968 * @return string User's preferred date format
2970 public function getDatePreference() {
2971 // Important migration for old data rows
2972 if ( is_null( $this->mDatePreference
) ) {
2974 $value = $this->getOption( 'date' );
2975 $map = $wgLang->getDatePreferenceMigrationMap();
2976 if ( isset( $map[$value] ) ) {
2977 $value = $map[$value];
2979 $this->mDatePreference
= $value;
2981 return $this->mDatePreference
;
2985 * Determine based on the wiki configuration and the user's options,
2986 * whether this user must be over HTTPS no matter what.
2990 public function requiresHTTPS() {
2991 global $wgSecureLogin;
2992 if ( !$wgSecureLogin ) {
2995 $https = $this->getBoolOption( 'prefershttps' );
2996 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2998 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3005 * Get the user preferred stub threshold
3009 public function getStubThreshold() {
3010 global $wgMaxArticleSize; # Maximum article size, in Kb
3011 $threshold = $this->getIntOption( 'stubthreshold' );
3012 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3013 // If they have set an impossible value, disable the preference
3014 // so we can use the parser cache again.
3021 * Get the permissions this user has.
3022 * @return array Array of String permission names
3024 public function getRights() {
3025 if ( is_null( $this->mRights
) ) {
3026 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3027 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
3028 // Force reindexation of rights when a hook has unset one of them
3029 $this->mRights
= array_values( array_unique( $this->mRights
) );
3031 return $this->mRights
;
3035 * Get the list of explicit group memberships this user has.
3036 * The implicit * and user groups are not included.
3037 * @return array Array of String internal group names
3039 public function getGroups() {
3041 $this->loadGroups();
3042 return $this->mGroups
;
3046 * Get the list of implicit group memberships this user has.
3047 * This includes all explicit groups, plus 'user' if logged in,
3048 * '*' for all accounts, and autopromoted groups
3049 * @param bool $recache Whether to avoid the cache
3050 * @return array Array of String internal group names
3052 public function getEffectiveGroups( $recache = false ) {
3053 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3054 $this->mEffectiveGroups
= array_unique( array_merge(
3055 $this->getGroups(), // explicit groups
3056 $this->getAutomaticGroups( $recache ) // implicit groups
3058 // Hook for additional groups
3059 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
3060 // Force reindexation of groups when a hook has unset one of them
3061 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3063 return $this->mEffectiveGroups
;
3067 * Get the list of implicit group memberships this user has.
3068 * This includes 'user' if logged in, '*' for all accounts,
3069 * and autopromoted groups
3070 * @param bool $recache Whether to avoid the cache
3071 * @return array Array of String internal group names
3073 public function getAutomaticGroups( $recache = false ) {
3074 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3075 $this->mImplicitGroups
= array( '*' );
3076 if ( $this->getId() ) {
3077 $this->mImplicitGroups
[] = 'user';
3079 $this->mImplicitGroups
= array_unique( array_merge(
3080 $this->mImplicitGroups
,
3081 Autopromote
::getAutopromoteGroups( $this )
3085 // Assure data consistency with rights/groups,
3086 // as getEffectiveGroups() depends on this function
3087 $this->mEffectiveGroups
= null;
3090 return $this->mImplicitGroups
;
3094 * Returns the groups the user has belonged to.
3096 * The user may still belong to the returned groups. Compare with getGroups().
3098 * The function will not return groups the user had belonged to before MW 1.17
3100 * @return array Names of the groups the user has belonged to.
3102 public function getFormerGroups() {
3105 if ( is_null( $this->mFormerGroups
) ) {
3106 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3107 ?
wfGetDB( DB_MASTER
)
3108 : wfGetDB( DB_SLAVE
);
3109 $res = $db->select( 'user_former_groups',
3110 array( 'ufg_group' ),
3111 array( 'ufg_user' => $this->mId
),
3113 $this->mFormerGroups
= array();
3114 foreach ( $res as $row ) {
3115 $this->mFormerGroups
[] = $row->ufg_group
;
3119 return $this->mFormerGroups
;
3123 * Get the user's edit count.
3124 * @return int|null Null for anonymous users
3126 public function getEditCount() {
3127 if ( !$this->getId() ) {
3131 if ( $this->mEditCount
=== null ) {
3132 /* Populate the count, if it has not been populated yet */
3133 $dbr = wfGetDB( DB_SLAVE
);
3134 // check if the user_editcount field has been initialized
3135 $count = $dbr->selectField(
3136 'user', 'user_editcount',
3137 array( 'user_id' => $this->mId
),
3141 if ( $count === null ) {
3142 // it has not been initialized. do so.
3143 $count = $this->initEditCount();
3145 $this->mEditCount
= $count;
3147 return (int)$this->mEditCount
;
3151 * Add the user to the given group.
3152 * This takes immediate effect.
3153 * @param string $group Name of the group to add
3156 public function addGroup( $group ) {
3159 if ( !Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3163 $dbw = wfGetDB( DB_MASTER
);
3164 if ( $this->getId() ) {
3165 $dbw->insert( 'user_groups',
3167 'ug_user' => $this->getID(),
3168 'ug_group' => $group,
3171 array( 'IGNORE' ) );
3174 $this->loadGroups();
3175 $this->mGroups
[] = $group;
3176 // In case loadGroups was not called before, we now have the right twice.
3177 // Get rid of the duplicate.
3178 $this->mGroups
= array_unique( $this->mGroups
);
3180 // Refresh the groups caches, and clear the rights cache so it will be
3181 // refreshed on the next call to $this->getRights().
3182 $this->getEffectiveGroups( true );
3183 $this->mRights
= null;
3185 $this->invalidateCache();
3191 * Remove the user from the given group.
3192 * This takes immediate effect.
3193 * @param string $group Name of the group to remove
3196 public function removeGroup( $group ) {
3198 if ( !Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3202 $dbw = wfGetDB( DB_MASTER
);
3203 $dbw->delete( 'user_groups',
3205 'ug_user' => $this->getID(),
3206 'ug_group' => $group,
3209 // Remember that the user was in this group
3210 $dbw->insert( 'user_former_groups',
3212 'ufg_user' => $this->getID(),
3213 'ufg_group' => $group,
3219 $this->loadGroups();
3220 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3222 // Refresh the groups caches, and clear the rights cache so it will be
3223 // refreshed on the next call to $this->getRights().
3224 $this->getEffectiveGroups( true );
3225 $this->mRights
= null;
3227 $this->invalidateCache();
3233 * Get whether the user is logged in
3236 public function isLoggedIn() {
3237 return $this->getID() != 0;
3241 * Get whether the user is anonymous
3244 public function isAnon() {
3245 return !$this->isLoggedIn();
3249 * Check if user is allowed to access a feature / make an action
3251 * @param string ... Permissions to test
3252 * @return bool True if user is allowed to perform *any* of the given actions
3254 public function isAllowedAny() {
3255 $permissions = func_get_args();
3256 foreach ( $permissions as $permission ) {
3257 if ( $this->isAllowed( $permission ) ) {
3266 * @param string ... Permissions to test
3267 * @return bool True if the user is allowed to perform *all* of the given actions
3269 public function isAllowedAll() {
3270 $permissions = func_get_args();
3271 foreach ( $permissions as $permission ) {
3272 if ( !$this->isAllowed( $permission ) ) {
3280 * Internal mechanics of testing a permission
3281 * @param string $action
3284 public function isAllowed( $action = '' ) {
3285 if ( $action === '' ) {
3286 return true; // In the spirit of DWIM
3288 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3289 // by misconfiguration: 0 == 'foo'
3290 return in_array( $action, $this->getRights(), true );
3294 * Check whether to enable recent changes patrol features for this user
3295 * @return bool True or false
3297 public function useRCPatrol() {
3298 global $wgUseRCPatrol;
3299 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3303 * Check whether to enable new pages patrol features for this user
3304 * @return bool True or false
3306 public function useNPPatrol() {
3307 global $wgUseRCPatrol, $wgUseNPPatrol;
3309 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3310 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3315 * Check whether to enable new files patrol features for this user
3316 * @return bool True or false
3318 public function useFilePatrol() {
3319 global $wgUseRCPatrol, $wgUseFilePatrol;
3321 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3322 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3327 * Get the WebRequest object to use with this object
3329 * @return WebRequest
3331 public function getRequest() {
3332 if ( $this->mRequest
) {
3333 return $this->mRequest
;
3341 * Get a WatchedItem for this user and $title.
3343 * @since 1.22 $checkRights parameter added
3344 * @param Title $title
3345 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3346 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3347 * @return WatchedItem
3349 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3350 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3352 if ( isset( $this->mWatchedItems
[$key] ) ) {
3353 return $this->mWatchedItems
[$key];
3356 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3357 $this->mWatchedItems
= array();
3360 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3361 return $this->mWatchedItems
[$key];
3365 * Check the watched status of an article.
3366 * @since 1.22 $checkRights parameter added
3367 * @param Title $title Title of the article to look at
3368 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3369 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3372 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3373 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3378 * @since 1.22 $checkRights parameter added
3379 * @param Title $title Title of the article to look at
3380 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3381 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3383 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3384 $this->getWatchedItem( $title, $checkRights )->addWatch();
3385 $this->invalidateCache();
3389 * Stop watching an article.
3390 * @since 1.22 $checkRights parameter added
3391 * @param Title $title Title of the article to look at
3392 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3393 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3395 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3396 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3397 $this->invalidateCache();
3401 * Clear the user's notification timestamp for the given title.
3402 * If e-notif e-mails are on, they will receive notification mails on
3403 * the next change of the page if it's watched etc.
3404 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3405 * @param Title $title Title of the article to look at
3406 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3408 public function clearNotification( &$title, $oldid = 0 ) {
3409 global $wgUseEnotif, $wgShowUpdatedMarker;
3411 // Do nothing if the database is locked to writes
3412 if ( wfReadOnly() ) {
3416 // Do nothing if not allowed to edit the watchlist
3417 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3421 // If we're working on user's talk page, we should update the talk page message indicator
3422 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3423 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3428 // Try to update the DB post-send and only if needed...
3429 DeferredUpdates
::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3430 if ( !$that->getNewtalk() ) {
3431 return; // no notifications to clear
3434 // Delete the last notifications (they stack up)
3435 $that->setNewtalk( false );
3437 // If there is a new, unseen, revision, use its timestamp
3439 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3442 $that->setNewtalk( true, Revision
::newFromId( $nextid ) );
3447 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3451 if ( $this->isAnon() ) {
3452 // Nothing else to do...
3456 // Only update the timestamp if the page is being watched.
3457 // The query to find out if it is watched is cached both in memcached and per-invocation,
3458 // and when it does have to be executed, it can be on a slave
3459 // If this is the user's newtalk page, we always update the timestamp
3461 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3465 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3471 * Resets all of the given user's page-change notification timestamps.
3472 * If e-notif e-mails are on, they will receive notification mails on
3473 * the next change of any watched page.
3474 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3476 public function clearAllNotifications() {
3477 if ( wfReadOnly() ) {
3481 // Do nothing if not allowed to edit the watchlist
3482 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3486 global $wgUseEnotif, $wgShowUpdatedMarker;
3487 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3488 $this->setNewtalk( false );
3491 $id = $this->getId();
3493 $dbw = wfGetDB( DB_MASTER
);
3494 $dbw->update( 'watchlist',
3495 array( /* SET */ 'wl_notificationtimestamp' => null ),
3496 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3499 // We also need to clear here the "you have new message" notification for the own user_talk page;
3500 // it's cleared one page view later in WikiPage::doViewUpdates().
3505 * Set a cookie on the user's client. Wrapper for
3506 * WebResponse::setCookie
3507 * @param string $name Name of the cookie to set
3508 * @param string $value Value to set
3509 * @param int $exp Expiration time, as a UNIX time value;
3510 * if 0 or not specified, use the default $wgCookieExpiration
3511 * @param bool $secure
3512 * true: Force setting the secure attribute when setting the cookie
3513 * false: Force NOT setting the secure attribute when setting the cookie
3514 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3515 * @param array $params Array of options sent passed to WebResponse::setcookie()
3516 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3519 protected function setCookie(
3520 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3522 if ( $request === null ) {
3523 $request = $this->getRequest();
3525 $params['secure'] = $secure;
3526 $request->response()->setCookie( $name, $value, $exp, $params );
3530 * Clear a cookie on the user's client
3531 * @param string $name Name of the cookie to clear
3532 * @param bool $secure
3533 * true: Force setting the secure attribute when setting the cookie
3534 * false: Force NOT setting the secure attribute when setting the cookie
3535 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3536 * @param array $params Array of options sent passed to WebResponse::setcookie()
3538 protected function clearCookie( $name, $secure = null, $params = array() ) {
3539 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3543 * Set an extended login cookie on the user's client. The expiry of the cookie
3544 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3547 * @see User::setCookie
3549 * @param string $name Name of the cookie to set
3550 * @param string $value Value to set
3551 * @param bool $secure
3552 * true: Force setting the secure attribute when setting the cookie
3553 * false: Force NOT setting the secure attribute when setting the cookie
3554 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3556 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3557 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3560 $exp +
= $wgExtendedLoginCookieExpiration !== null
3561 ?
$wgExtendedLoginCookieExpiration
3562 : $wgCookieExpiration;
3564 $this->setCookie( $name, $value, $exp, $secure );
3568 * Set the default cookies for this session on the user's client.
3570 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3572 * @param bool $secure Whether to force secure/insecure cookies or use default
3573 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3575 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3576 global $wgExtendedLoginCookies;
3578 if ( $request === null ) {
3579 $request = $this->getRequest();
3583 if ( 0 == $this->mId
) {
3586 if ( !$this->mToken
) {
3587 // When token is empty or NULL generate a new one and then save it to the database
3588 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3589 // Simply by setting every cell in the user_token column to NULL and letting them be
3590 // regenerated as users log back into the wiki.
3592 if ( !wfReadOnly() ) {
3593 $this->saveSettings();
3597 'wsUserID' => $this->mId
,
3598 'wsToken' => $this->mToken
,
3599 'wsUserName' => $this->getName()
3602 'UserID' => $this->mId
,
3603 'UserName' => $this->getName(),
3605 if ( $rememberMe ) {
3606 $cookies['Token'] = $this->mToken
;
3608 $cookies['Token'] = false;
3611 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3613 foreach ( $session as $name => $value ) {
3614 $request->setSessionData( $name, $value );
3616 foreach ( $cookies as $name => $value ) {
3617 if ( $value === false ) {
3618 $this->clearCookie( $name );
3619 } elseif ( $rememberMe && in_array( $name, $wgExtendedLoginCookies ) ) {
3620 $this->setExtendedLoginCookie( $name, $value, $secure );
3622 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3627 * If wpStickHTTPS was selected, also set an insecure cookie that
3628 * will cause the site to redirect the user to HTTPS, if they access
3629 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3630 * as the one set by centralauth (bug 53538). Also set it to session, or
3631 * standard time setting, based on if rememberme was set.
3633 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3637 $rememberMe ?
0 : null,
3639 array( 'prefix' => '' ) // no prefix
3645 * Log this user out.
3647 public function logout() {
3648 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3654 * Clear the user's cookies and session, and reset the instance cache.
3657 public function doLogout() {
3658 $this->clearInstanceCache( 'defaults' );
3660 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3662 $this->clearCookie( 'UserID' );
3663 $this->clearCookie( 'Token' );
3664 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3666 // Remember when user logged out, to prevent seeing cached pages
3667 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3671 * Save this user's settings into the database.
3672 * @todo Only rarely do all these fields need to be set!
3674 public function saveSettings() {
3675 if ( wfReadOnly() ) {
3676 // @TODO: caller should deal with this instead!
3677 // This should really just be an exception.
3678 MWExceptionHandler
::logException( new DBExpectedError(
3680 "Could not update user with ID '{$this->mId}'; DB is read-only."
3686 if ( 0 == $this->mId
) {
3690 // Get a new user_touched that is higher than the old one.
3691 // This will be used for a CAS check as a last-resort safety
3692 // check against race conditions and slave lag.
3693 $oldTouched = $this->mTouched
;
3694 $newTouched = $this->newTouchedTimestamp();
3696 $dbw = wfGetDB( DB_MASTER
);
3697 $dbw->update( 'user',
3699 'user_name' => $this->mName
,
3700 'user_real_name' => $this->mRealName
,
3701 'user_email' => $this->mEmail
,
3702 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3703 'user_touched' => $dbw->timestamp( $newTouched ),
3704 'user_token' => strval( $this->mToken
),
3705 'user_email_token' => $this->mEmailToken
,
3706 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3707 ), array( /* WHERE */
3708 'user_id' => $this->mId
,
3709 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3713 if ( !$dbw->affectedRows() ) {
3714 // Maybe the problem was a missed cache update; clear it to be safe
3715 $this->clearSharedCache( 'refresh' );
3716 // User was changed in the meantime or loaded with stale data
3717 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'slave';
3718 throw new MWException(
3719 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3720 " the version of the user to be saved is older than the current version."
3724 $this->mTouched
= $newTouched;
3725 $this->saveOptions();
3727 Hooks
::run( 'UserSaveSettings', array( $this ) );
3728 $this->clearSharedCache();
3729 $this->getUserPage()->invalidateCache();
3733 * If only this user's username is known, and it exists, return the user ID.
3735 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3738 public function idForName( $flags = 0 ) {
3739 $s = trim( $this->getName() );
3744 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3745 ?
wfGetDB( DB_MASTER
)
3746 : wfGetDB( DB_SLAVE
);
3748 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3749 ?
array( 'LOCK IN SHARE MODE' )
3752 $id = $db->selectField( 'user',
3753 'user_id', array( 'user_name' => $s ), __METHOD__
, $options );
3759 * Add a user to the database, return the user object
3761 * @param string $name Username to add
3762 * @param array $params Array of Strings Non-default parameters to save to
3763 * the database as user_* fields:
3764 * - email: The user's email address.
3765 * - email_authenticated: The email authentication timestamp.
3766 * - real_name: The user's real name.
3767 * - options: An associative array of non-default options.
3768 * - token: Random authentication token. Do not set.
3769 * - registration: Registration timestamp. Do not set.
3771 * @return User|null User object, or null if the username already exists.
3773 public static function createNew( $name, $params = array() ) {
3774 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3775 if ( isset( $params[$field] ) ) {
3776 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3777 unset( $params[$field] );
3783 $user->setToken(); // init token
3784 if ( isset( $params['options'] ) ) {
3785 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3786 unset( $params['options'] );
3788 $dbw = wfGetDB( DB_MASTER
);
3789 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3791 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3794 'user_id' => $seqVal,
3795 'user_name' => $name,
3796 'user_password' => $noPass,
3797 'user_newpassword' => $noPass,
3798 'user_email' => $user->mEmail
,
3799 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3800 'user_real_name' => $user->mRealName
,
3801 'user_token' => strval( $user->mToken
),
3802 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3803 'user_editcount' => 0,
3804 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3806 foreach ( $params as $name => $value ) {
3807 $fields["user_$name"] = $value;
3809 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3810 if ( $dbw->affectedRows() ) {
3811 $newUser = User
::newFromId( $dbw->insertId() );
3819 * Add this existing user object to the database. If the user already
3820 * exists, a fatal status object is returned, and the user object is
3821 * initialised with the data from the database.
3823 * Previously, this function generated a DB error due to a key conflict
3824 * if the user already existed. Many extension callers use this function
3825 * in code along the lines of:
3827 * $user = User::newFromName( $name );
3828 * if ( !$user->isLoggedIn() ) {
3829 * $user->addToDatabase();
3831 * // do something with $user...
3833 * However, this was vulnerable to a race condition (bug 16020). By
3834 * initialising the user object if the user exists, we aim to support this
3835 * calling sequence as far as possible.
3837 * Note that if the user exists, this function will acquire a write lock,
3838 * so it is still advisable to make the call conditional on isLoggedIn(),
3839 * and to commit the transaction after calling.
3841 * @throws MWException
3844 public function addToDatabase() {
3846 if ( !$this->mToken
) {
3847 $this->setToken(); // init token
3850 $this->mTouched
= $this->newTouchedTimestamp();
3852 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3854 $dbw = wfGetDB( DB_MASTER
);
3855 $inWrite = $dbw->writesOrCallbacksPending();
3856 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3857 $dbw->insert( 'user',
3859 'user_id' => $seqVal,
3860 'user_name' => $this->mName
,
3861 'user_password' => $noPass,
3862 'user_newpassword' => $noPass,
3863 'user_email' => $this->mEmail
,
3864 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3865 'user_real_name' => $this->mRealName
,
3866 'user_token' => strval( $this->mToken
),
3867 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3868 'user_editcount' => 0,
3869 'user_touched' => $dbw->timestamp( $this->mTouched
),
3873 if ( !$dbw->affectedRows() ) {
3874 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3875 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3877 // Can't commit due to pending writes that may need atomicity.
3878 // This may cause some lock contention unlike the case below.
3879 $options = array( 'LOCK IN SHARE MODE' );
3880 $flags = self
::READ_LOCKING
;
3882 // Often, this case happens early in views before any writes when
3883 // using CentralAuth. It's should be OK to commit and break the snapshot.
3884 $dbw->commit( __METHOD__
, 'flush' );
3886 $flags = self
::READ_LATEST
;
3888 $this->mId
= $dbw->selectField( 'user', 'user_id',
3889 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3892 if ( $this->loadFromDatabase( $flags ) ) {
3897 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3898 "to insert user '{$this->mName}' row, but it was not present in select!" );
3900 return Status
::newFatal( 'userexists' );
3902 $this->mId
= $dbw->insertId();
3903 self
::$idCacheByName[$this->mName
] = $this->mId
;
3905 // Clear instance cache other than user table data, which is already accurate
3906 $this->clearInstanceCache();
3908 $this->saveOptions();
3909 return Status
::newGood();
3913 * If this user is logged-in and blocked,
3914 * block any IP address they've successfully logged in from.
3915 * @return bool A block was spread
3917 public function spreadAnyEditBlock() {
3918 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3919 return $this->spreadBlock();
3925 * If this (non-anonymous) user is blocked,
3926 * block the IP address they've successfully logged in from.
3927 * @return bool A block was spread
3929 protected function spreadBlock() {
3930 wfDebug( __METHOD__
. "()\n" );
3932 if ( $this->mId
== 0 ) {
3936 $userblock = Block
::newFromTarget( $this->getName() );
3937 if ( !$userblock ) {
3941 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3945 * Get whether the user is explicitly blocked from account creation.
3946 * @return bool|Block
3948 public function isBlockedFromCreateAccount() {
3949 $this->getBlockedStatus();
3950 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3951 return $this->mBlock
;
3954 # bug 13611: if the IP address the user is trying to create an account from is
3955 # blocked with createaccount disabled, prevent new account creation there even
3956 # when the user is logged in
3957 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3958 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3960 return $this->mBlockedFromCreateAccount
instanceof Block
3961 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3962 ?
$this->mBlockedFromCreateAccount
3967 * Get whether the user is blocked from using Special:Emailuser.
3970 public function isBlockedFromEmailuser() {
3971 $this->getBlockedStatus();
3972 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3976 * Get whether the user is allowed to create an account.
3979 public function isAllowedToCreateAccount() {
3980 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3984 * Get this user's personal page title.
3986 * @return Title User's personal page title
3988 public function getUserPage() {
3989 return Title
::makeTitle( NS_USER
, $this->getName() );
3993 * Get this user's talk page title.
3995 * @return Title User's talk page title
3997 public function getTalkPage() {
3998 $title = $this->getUserPage();
3999 return $title->getTalkPage();
4003 * Determine whether the user is a newbie. Newbies are either
4004 * anonymous IPs, or the most recently created accounts.
4007 public function isNewbie() {
4008 return !$this->isAllowed( 'autoconfirmed' );
4012 * Check to see if the given clear-text password is one of the accepted passwords
4013 * @deprecated since 1.27. AuthManager is coming.
4014 * @param string $password User password
4015 * @return bool True if the given password is correct, otherwise False
4017 public function checkPassword( $password ) {
4018 global $wgAuth, $wgLegacyEncoding;
4022 // Some passwords will give a fatal Status, which means there is
4023 // some sort of technical or security reason for this password to
4024 // be completely invalid and should never be checked (e.g., T64685)
4025 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4029 // Certain authentication plugins do NOT want to save
4030 // domain passwords in a mysql database, so we should
4031 // check this (in case $wgAuth->strict() is false).
4032 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4034 } elseif ( $wgAuth->strict() ) {
4035 // Auth plugin doesn't allow local authentication
4037 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4038 // Auth plugin doesn't allow local authentication for this user name
4042 $passwordFactory = new PasswordFactory();
4043 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4044 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4045 ?
wfGetDB( DB_MASTER
)
4046 : wfGetDB( DB_SLAVE
);
4049 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4050 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4052 } catch ( PasswordError
$e ) {
4053 wfDebug( 'Invalid password hash found in database.' );
4054 $mPassword = PasswordFactory
::newInvalidPassword();
4057 if ( !$mPassword->equals( $password ) ) {
4058 if ( $wgLegacyEncoding ) {
4059 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4060 // Check for this with iconv
4061 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4062 if ( $cp1252Password === $password ||
!$mPassword->equals( $cp1252Password ) ) {
4070 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4071 $this->setPasswordInternal( $password );
4078 * Check if the given clear-text password matches the temporary password
4079 * sent by e-mail for password reset operations.
4081 * @deprecated since 1.27. AuthManager is coming.
4082 * @param string $plaintext
4083 * @return bool True if matches, false otherwise
4085 public function checkTemporaryPassword( $plaintext ) {
4086 global $wgNewPasswordExpiry;
4090 $passwordFactory = new PasswordFactory();
4091 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4092 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
4093 ?
wfGetDB( DB_MASTER
)
4094 : wfGetDB( DB_SLAVE
);
4096 $row = $db->selectRow(
4098 array( 'user_newpassword', 'user_newpass_time' ),
4099 array( 'user_id' => $this->getId() ),
4103 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword
);
4104 } catch ( PasswordError
$e ) {
4105 wfDebug( 'Invalid password hash found in database.' );
4106 $newPassword = PasswordFactory
::newInvalidPassword();
4109 if ( $newPassword->equals( $plaintext ) ) {
4110 if ( is_null( $row->user_newpass_time
) ) {
4113 $expiry = wfTimestamp( TS_UNIX
, $row->user_newpass_time
) +
$wgNewPasswordExpiry;
4114 return ( time() < $expiry );
4121 * Internal implementation for self::getEditToken() and
4122 * self::matchEditToken().
4124 * @param string|array $salt
4125 * @param WebRequest $request
4126 * @param string|int $timestamp
4129 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4130 if ( $this->isAnon() ) {
4131 return self
::EDIT_TOKEN_SUFFIX
;
4133 $token = $request->getSessionData( 'wsEditToken' );
4134 if ( $token === null ) {
4135 $token = MWCryptRand
::generateHex( 32 );
4136 $request->setSessionData( 'wsEditToken', $token );
4138 if ( is_array( $salt ) ) {
4139 $salt = implode( '|', $salt );
4141 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4142 dechex( $timestamp ) .
4143 self
::EDIT_TOKEN_SUFFIX
;
4148 * Initialize (if necessary) and return a session token value
4149 * which can be used in edit forms to show that the user's
4150 * login credentials aren't being hijacked with a foreign form
4155 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4156 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4157 * @return string The new edit token
4159 public function getEditToken( $salt = '', $request = null ) {
4160 return $this->getEditTokenAtTimestamp(
4161 $salt, $request ?
: $this->getRequest(), wfTimestamp()
4166 * Get the embedded timestamp from a token.
4167 * @param string $val Input token
4170 public static function getEditTokenTimestamp( $val ) {
4171 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
4172 if ( strlen( $val ) <= 32 +
$suffixLen ) {
4176 return hexdec( substr( $val, 32, -$suffixLen ) );
4180 * Check given value against the token value stored in the session.
4181 * A match should confirm that the form was submitted from the
4182 * user's own login session, not a form submission from a third-party
4185 * @param string $val Input value to compare
4186 * @param string $salt Optional function-specific data for hashing
4187 * @param WebRequest|null $request Object to use or null to use $wgRequest
4188 * @param int $maxage Fail tokens older than this, in seconds
4189 * @return bool Whether the token matches
4191 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4192 if ( $this->isAnon() ) {
4193 return $val === self
::EDIT_TOKEN_SUFFIX
;
4196 $timestamp = self
::getEditTokenTimestamp( $val );
4197 if ( $timestamp === null ) {
4200 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4205 $sessionToken = $this->getEditTokenAtTimestamp(
4206 $salt, $request ?
: $this->getRequest(), $timestamp
4209 if ( !hash_equals( $sessionToken, $val ) ) {
4210 wfDebug( "User::matchEditToken: broken session data\n" );
4213 return hash_equals( $sessionToken, $val );
4217 * Check given value against the token value stored in the session,
4218 * ignoring the suffix.
4220 * @param string $val Input value to compare
4221 * @param string $salt Optional function-specific data for hashing
4222 * @param WebRequest|null $request Object to use or null to use $wgRequest
4223 * @param int $maxage Fail tokens older than this, in seconds
4224 * @return bool Whether the token matches
4226 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4227 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
4228 return $this->matchEditToken( $val, $salt, $request, $maxage );
4232 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4233 * mail to the user's given address.
4235 * @param string $type Message to send, either "created", "changed" or "set"
4238 public function sendConfirmationMail( $type = 'created' ) {
4240 $expiration = null; // gets passed-by-ref and defined in next line.
4241 $token = $this->confirmationToken( $expiration );
4242 $url = $this->confirmationTokenUrl( $token );
4243 $invalidateURL = $this->invalidationTokenUrl( $token );
4244 $this->saveSettings();
4246 if ( $type == 'created' ||
$type === false ) {
4247 $message = 'confirmemail_body';
4248 } elseif ( $type === true ) {
4249 $message = 'confirmemail_body_changed';
4251 // Messages: confirmemail_body_changed, confirmemail_body_set
4252 $message = 'confirmemail_body_' . $type;
4255 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4256 wfMessage( $message,
4257 $this->getRequest()->getIP(),
4260 $wgLang->userTimeAndDate( $expiration, $this ),
4262 $wgLang->userDate( $expiration, $this ),
4263 $wgLang->userTime( $expiration, $this ) )->text() );
4267 * Send an e-mail to this user's account. Does not check for
4268 * confirmed status or validity.
4270 * @param string $subject Message subject
4271 * @param string $body Message body
4272 * @param User|null $from Optional sending user; if unspecified, default
4273 * $wgPasswordSender will be used.
4274 * @param string $replyto Reply-To address
4277 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4278 global $wgPasswordSender;
4280 if ( $from instanceof User
) {
4281 $sender = MailAddress
::newFromUser( $from );
4283 $sender = new MailAddress( $wgPasswordSender,
4284 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4286 $to = MailAddress
::newFromUser( $this );
4288 return UserMailer
::send( $to, $sender, $subject, $body, array(
4289 'replyTo' => $replyto,
4294 * Generate, store, and return a new e-mail confirmation code.
4295 * A hash (unsalted, since it's used as a key) is stored.
4297 * @note Call saveSettings() after calling this function to commit
4298 * this change to the database.
4300 * @param string &$expiration Accepts the expiration time
4301 * @return string New token
4303 protected function confirmationToken( &$expiration ) {
4304 global $wgUserEmailConfirmationTokenExpiry;
4306 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4307 $expiration = wfTimestamp( TS_MW
, $expires );
4309 $token = MWCryptRand
::generateHex( 32 );
4310 $hash = md5( $token );
4311 $this->mEmailToken
= $hash;
4312 $this->mEmailTokenExpires
= $expiration;
4317 * Return a URL the user can use to confirm their email address.
4318 * @param string $token Accepts the email confirmation token
4319 * @return string New token URL
4321 protected function confirmationTokenUrl( $token ) {
4322 return $this->getTokenUrl( 'ConfirmEmail', $token );
4326 * Return a URL the user can use to invalidate their email address.
4327 * @param string $token Accepts the email confirmation token
4328 * @return string New token URL
4330 protected function invalidationTokenUrl( $token ) {
4331 return $this->getTokenUrl( 'InvalidateEmail', $token );
4335 * Internal function to format the e-mail validation/invalidation URLs.
4336 * This uses a quickie hack to use the
4337 * hardcoded English names of the Special: pages, for ASCII safety.
4339 * @note Since these URLs get dropped directly into emails, using the
4340 * short English names avoids insanely long URL-encoded links, which
4341 * also sometimes can get corrupted in some browsers/mailers
4342 * (bug 6957 with Gmail and Internet Explorer).
4344 * @param string $page Special page
4345 * @param string $token Token
4346 * @return string Formatted URL
4348 protected function getTokenUrl( $page, $token ) {
4349 // Hack to bypass localization of 'Special:'
4350 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4351 return $title->getCanonicalURL();
4355 * Mark the e-mail address confirmed.
4357 * @note Call saveSettings() after calling this function to commit the change.
4361 public function confirmEmail() {
4362 // Check if it's already confirmed, so we don't touch the database
4363 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4364 if ( !$this->isEmailConfirmed() ) {
4365 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4366 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4372 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4373 * address if it was already confirmed.
4375 * @note Call saveSettings() after calling this function to commit the change.
4376 * @return bool Returns true
4378 public function invalidateEmail() {
4380 $this->mEmailToken
= null;
4381 $this->mEmailTokenExpires
= null;
4382 $this->setEmailAuthenticationTimestamp( null );
4384 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4389 * Set the e-mail authentication timestamp.
4390 * @param string $timestamp TS_MW timestamp
4392 public function setEmailAuthenticationTimestamp( $timestamp ) {
4394 $this->mEmailAuthenticated
= $timestamp;
4395 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4399 * Is this user allowed to send e-mails within limits of current
4400 * site configuration?
4403 public function canSendEmail() {
4404 global $wgEnableEmail, $wgEnableUserEmail;
4405 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4408 $canSend = $this->isEmailConfirmed();
4409 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4414 * Is this user allowed to receive e-mails within limits of current
4415 * site configuration?
4418 public function canReceiveEmail() {
4419 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4423 * Is this user's e-mail address valid-looking and confirmed within
4424 * limits of the current site configuration?
4426 * @note If $wgEmailAuthentication is on, this may require the user to have
4427 * confirmed their address by returning a code or using a password
4428 * sent to the address from the wiki.
4432 public function isEmailConfirmed() {
4433 global $wgEmailAuthentication;
4436 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4437 if ( $this->isAnon() ) {
4440 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4443 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4453 * Check whether there is an outstanding request for e-mail confirmation.
4456 public function isEmailConfirmationPending() {
4457 global $wgEmailAuthentication;
4458 return $wgEmailAuthentication &&
4459 !$this->isEmailConfirmed() &&
4460 $this->mEmailToken
&&
4461 $this->mEmailTokenExpires
> wfTimestamp();
4465 * Get the timestamp of account creation.
4467 * @return string|bool|null Timestamp of account creation, false for
4468 * non-existent/anonymous user accounts, or null if existing account
4469 * but information is not in database.
4471 public function getRegistration() {
4472 if ( $this->isAnon() ) {
4476 return $this->mRegistration
;
4480 * Get the timestamp of the first edit
4482 * @return string|bool Timestamp of first edit, or false for
4483 * non-existent/anonymous user accounts.
4485 public function getFirstEditTimestamp() {
4486 if ( $this->getId() == 0 ) {
4487 return false; // anons
4489 $dbr = wfGetDB( DB_SLAVE
);
4490 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4491 array( 'rev_user' => $this->getId() ),
4493 array( 'ORDER BY' => 'rev_timestamp ASC' )
4496 return false; // no edits
4498 return wfTimestamp( TS_MW
, $time );
4502 * Get the permissions associated with a given list of groups
4504 * @param array $groups Array of Strings List of internal group names
4505 * @return array Array of Strings List of permission key names for given groups combined
4507 public static function getGroupPermissions( $groups ) {
4508 global $wgGroupPermissions, $wgRevokePermissions;
4510 // grant every granted permission first
4511 foreach ( $groups as $group ) {
4512 if ( isset( $wgGroupPermissions[$group] ) ) {
4513 $rights = array_merge( $rights,
4514 // array_filter removes empty items
4515 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4518 // now revoke the revoked permissions
4519 foreach ( $groups as $group ) {
4520 if ( isset( $wgRevokePermissions[$group] ) ) {
4521 $rights = array_diff( $rights,
4522 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4525 return array_unique( $rights );
4529 * Get all the groups who have a given permission
4531 * @param string $role Role to check
4532 * @return array Array of Strings List of internal group names with the given permission
4534 public static function getGroupsWithPermission( $role ) {
4535 global $wgGroupPermissions;
4536 $allowedGroups = array();
4537 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4538 if ( self
::groupHasPermission( $group, $role ) ) {
4539 $allowedGroups[] = $group;
4542 return $allowedGroups;
4546 * Check, if the given group has the given permission
4548 * If you're wanting to check whether all users have a permission, use
4549 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4553 * @param string $group Group to check
4554 * @param string $role Role to check
4557 public static function groupHasPermission( $group, $role ) {
4558 global $wgGroupPermissions, $wgRevokePermissions;
4559 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4560 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4564 * Check if all users may be assumed to have the given permission
4566 * We generally assume so if the right is granted to '*' and isn't revoked
4567 * on any group. It doesn't attempt to take grants or other extension
4568 * limitations on rights into account in the general case, though, as that
4569 * would require it to always return false and defeat the purpose.
4570 * Specifically, session-based rights restrictions (such as OAuth or bot
4571 * passwords) are applied based on the current session.
4574 * @param string $right Right to check
4577 public static function isEveryoneAllowed( $right ) {
4578 global $wgGroupPermissions, $wgRevokePermissions;
4579 static $cache = array();
4581 // Use the cached results, except in unit tests which rely on
4582 // being able change the permission mid-request
4583 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4584 return $cache[$right];
4587 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4588 $cache[$right] = false;
4592 // If it's revoked anywhere, then everyone doesn't have it
4593 foreach ( $wgRevokePermissions as $rights ) {
4594 if ( isset( $rights[$right] ) && $rights[$right] ) {
4595 $cache[$right] = false;
4600 // Allow extensions to say false
4601 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4602 $cache[$right] = false;
4606 $cache[$right] = true;
4611 * Get the localized descriptive name for a group, if it exists
4613 * @param string $group Internal group name
4614 * @return string Localized descriptive group name
4616 public static function getGroupName( $group ) {
4617 $msg = wfMessage( "group-$group" );
4618 return $msg->isBlank() ?
$group : $msg->text();
4622 * Get the localized descriptive name for a member of a group, if it exists
4624 * @param string $group Internal group name
4625 * @param string $username Username for gender (since 1.19)
4626 * @return string Localized name for group member
4628 public static function getGroupMember( $group, $username = '#' ) {
4629 $msg = wfMessage( "group-$group-member", $username );
4630 return $msg->isBlank() ?
$group : $msg->text();
4634 * Return the set of defined explicit groups.
4635 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4636 * are not included, as they are defined automatically, not in the database.
4637 * @return array Array of internal group names
4639 public static function getAllGroups() {
4640 global $wgGroupPermissions, $wgRevokePermissions;
4642 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4643 self
::getImplicitGroups()
4648 * Get a list of all available permissions.
4649 * @return string[] Array of permission names
4651 public static function getAllRights() {
4652 if ( self
::$mAllRights === false ) {
4653 global $wgAvailableRights;
4654 if ( count( $wgAvailableRights ) ) {
4655 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4657 self
::$mAllRights = self
::$mCoreRights;
4659 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4661 return self
::$mAllRights;
4665 * Get a list of implicit groups
4666 * @return array Array of Strings Array of internal group names
4668 public static function getImplicitGroups() {
4669 global $wgImplicitGroups;
4671 $groups = $wgImplicitGroups;
4672 # Deprecated, use $wgImplicitGroups instead
4673 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4679 * Get the title of a page describing a particular group
4681 * @param string $group Internal group name
4682 * @return Title|bool Title of the page if it exists, false otherwise
4684 public static function getGroupPage( $group ) {
4685 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4686 if ( $msg->exists() ) {
4687 $title = Title
::newFromText( $msg->text() );
4688 if ( is_object( $title ) ) {
4696 * Create a link to the group in HTML, if available;
4697 * else return the group name.
4699 * @param string $group Internal name of the group
4700 * @param string $text The text of the link
4701 * @return string HTML link to the group
4703 public static function makeGroupLinkHTML( $group, $text = '' ) {
4704 if ( $text == '' ) {
4705 $text = self
::getGroupName( $group );
4707 $title = self
::getGroupPage( $group );
4709 return Linker
::link( $title, htmlspecialchars( $text ) );
4711 return htmlspecialchars( $text );
4716 * Create a link to the group in Wikitext, if available;
4717 * else return the group name.
4719 * @param string $group Internal name of the group
4720 * @param string $text The text of the link
4721 * @return string Wikilink to the group
4723 public static function makeGroupLinkWiki( $group, $text = '' ) {
4724 if ( $text == '' ) {
4725 $text = self
::getGroupName( $group );
4727 $title = self
::getGroupPage( $group );
4729 $page = $title->getFullText();
4730 return "[[$page|$text]]";
4737 * Returns an array of the groups that a particular group can add/remove.
4739 * @param string $group The group to check for whether it can add/remove
4740 * @return array Array( 'add' => array( addablegroups ),
4741 * 'remove' => array( removablegroups ),
4742 * 'add-self' => array( addablegroups to self),
4743 * 'remove-self' => array( removable groups from self) )
4745 public static function changeableByGroup( $group ) {
4746 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4750 'remove' => array(),
4751 'add-self' => array(),
4752 'remove-self' => array()
4755 if ( empty( $wgAddGroups[$group] ) ) {
4756 // Don't add anything to $groups
4757 } elseif ( $wgAddGroups[$group] === true ) {
4758 // You get everything
4759 $groups['add'] = self
::getAllGroups();
4760 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4761 $groups['add'] = $wgAddGroups[$group];
4764 // Same thing for remove
4765 if ( empty( $wgRemoveGroups[$group] ) ) {
4767 } elseif ( $wgRemoveGroups[$group] === true ) {
4768 $groups['remove'] = self
::getAllGroups();
4769 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4770 $groups['remove'] = $wgRemoveGroups[$group];
4773 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4774 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4775 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4776 if ( is_int( $key ) ) {
4777 $wgGroupsAddToSelf['user'][] = $value;
4782 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4783 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4784 if ( is_int( $key ) ) {
4785 $wgGroupsRemoveFromSelf['user'][] = $value;
4790 // Now figure out what groups the user can add to him/herself
4791 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4793 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4794 // No idea WHY this would be used, but it's there
4795 $groups['add-self'] = User
::getAllGroups();
4796 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4797 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4800 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4802 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4803 $groups['remove-self'] = User
::getAllGroups();
4804 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4805 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4812 * Returns an array of groups that this user can add and remove
4813 * @return array Array( 'add' => array( addablegroups ),
4814 * 'remove' => array( removablegroups ),
4815 * 'add-self' => array( addablegroups to self),
4816 * 'remove-self' => array( removable groups from self) )
4818 public function changeableGroups() {
4819 if ( $this->isAllowed( 'userrights' ) ) {
4820 // This group gives the right to modify everything (reverse-
4821 // compatibility with old "userrights lets you change
4823 // Using array_merge to make the groups reindexed
4824 $all = array_merge( User
::getAllGroups() );
4828 'add-self' => array(),
4829 'remove-self' => array()
4833 // Okay, it's not so simple, we will have to go through the arrays
4836 'remove' => array(),
4837 'add-self' => array(),
4838 'remove-self' => array()
4840 $addergroups = $this->getEffectiveGroups();
4842 foreach ( $addergroups as $addergroup ) {
4843 $groups = array_merge_recursive(
4844 $groups, $this->changeableByGroup( $addergroup )
4846 $groups['add'] = array_unique( $groups['add'] );
4847 $groups['remove'] = array_unique( $groups['remove'] );
4848 $groups['add-self'] = array_unique( $groups['add-self'] );
4849 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4855 * Deferred version of incEditCountImmediate()
4857 public function incEditCount() {
4859 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle( function() use ( $that ) {
4860 $that->incEditCountImmediate();
4865 * Increment the user's edit-count field.
4866 * Will have no effect for anonymous users.
4869 public function incEditCountImmediate() {
4870 if ( $this->isAnon() ) {
4874 $dbw = wfGetDB( DB_MASTER
);
4875 // No rows will be "affected" if user_editcount is NULL
4878 array( 'user_editcount=user_editcount+1' ),
4879 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4882 // Lazy initialization check...
4883 if ( $dbw->affectedRows() == 0 ) {
4884 // Now here's a goddamn hack...
4885 $dbr = wfGetDB( DB_SLAVE
);
4886 if ( $dbr !== $dbw ) {
4887 // If we actually have a slave server, the count is
4888 // at least one behind because the current transaction
4889 // has not been committed and replicated.
4890 $this->initEditCount( 1 );
4892 // But if DB_SLAVE is selecting the master, then the
4893 // count we just read includes the revision that was
4894 // just added in the working transaction.
4895 $this->initEditCount();
4898 // Edit count in user cache too
4899 $this->invalidateCache();
4903 * Initialize user_editcount from data out of the revision table
4905 * @param int $add Edits to add to the count from the revision table
4906 * @return int Number of edits
4908 protected function initEditCount( $add = 0 ) {
4909 // Pull from a slave to be less cruel to servers
4910 // Accuracy isn't the point anyway here
4911 $dbr = wfGetDB( DB_SLAVE
);
4912 $count = (int)$dbr->selectField(
4915 array( 'rev_user' => $this->getId() ),
4918 $count = $count +
$add;
4920 $dbw = wfGetDB( DB_MASTER
);
4923 array( 'user_editcount' => $count ),
4924 array( 'user_id' => $this->getId() ),
4932 * Get the description of a given right
4934 * @param string $right Right to query
4935 * @return string Localized description of the right
4937 public static function getRightDescription( $right ) {
4938 $key = "right-$right";
4939 $msg = wfMessage( $key );
4940 return $msg->isBlank() ?
$right : $msg->text();
4944 * Make a new-style password hash
4946 * @param string $password Plain-text password
4947 * @param bool|string $salt Optional salt, may be random or the user ID.
4948 * If unspecified or false, will generate one automatically
4949 * @return string Password hash
4950 * @deprecated since 1.24, use Password class
4952 public static function crypt( $password, $salt = false ) {
4953 wfDeprecated( __METHOD__
, '1.24' );
4954 $passwordFactory = new PasswordFactory();
4955 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4956 $hash = $passwordFactory->newFromPlaintext( $password );
4957 return $hash->toString();
4961 * Compare a password hash with a plain-text password. Requires the user
4962 * ID if there's a chance that the hash is an old-style hash.
4964 * @param string $hash Password hash
4965 * @param string $password Plain-text password to compare
4966 * @param string|bool $userId User ID for old-style password salt
4969 * @deprecated since 1.24, use Password class
4971 public static function comparePasswords( $hash, $password, $userId = false ) {
4972 wfDeprecated( __METHOD__
, '1.24' );
4974 // Check for *really* old password hashes that don't even have a type
4975 // The old hash format was just an md5 hex hash, with no type information
4976 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4977 global $wgPasswordSalt;
4978 if ( $wgPasswordSalt ) {
4979 $password = ":B:{$userId}:{$hash}";
4981 $password = ":A:{$hash}";
4985 $passwordFactory = new PasswordFactory();
4986 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
4987 $hash = $passwordFactory->newFromCiphertext( $hash );
4988 return $hash->equals( $password );
4992 * Add a newuser log entry for this user.
4993 * Before 1.19 the return value was always true.
4995 * @param string|bool $action Account creation type.
4996 * - String, one of the following values:
4997 * - 'create' for an anonymous user creating an account for himself.
4998 * This will force the action's performer to be the created user itself,
4999 * no matter the value of $wgUser
5000 * - 'create2' for a logged in user creating an account for someone else
5001 * - 'byemail' when the created user will receive its password by e-mail
5002 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5003 * - Boolean means whether the account was created by e-mail (deprecated):
5004 * - true will be converted to 'byemail'
5005 * - false will be converted to 'create' if this object is the same as
5006 * $wgUser and to 'create2' otherwise
5008 * @param string $reason User supplied reason
5010 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5012 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5013 global $wgUser, $wgNewUserLog;
5014 if ( empty( $wgNewUserLog ) ) {
5015 return true; // disabled
5018 if ( $action === true ) {
5019 $action = 'byemail';
5020 } elseif ( $action === false ) {
5021 if ( $this->equals( $wgUser ) ) {
5024 $action = 'create2';
5028 if ( $action === 'create' ||
$action === 'autocreate' ) {
5031 $performer = $wgUser;
5034 $logEntry = new ManualLogEntry( 'newusers', $action );
5035 $logEntry->setPerformer( $performer );
5036 $logEntry->setTarget( $this->getUserPage() );
5037 $logEntry->setComment( $reason );
5038 $logEntry->setParameters( array(
5039 '4::userid' => $this->getId(),
5041 $logid = $logEntry->insert();
5043 if ( $action !== 'autocreate' ) {
5044 $logEntry->publish( $logid );
5051 * Add an autocreate newuser log entry for this user
5052 * Used by things like CentralAuth and perhaps other authplugins.
5053 * Consider calling addNewUserLogEntry() directly instead.
5057 public function addNewUserLogEntryAutoCreate() {
5058 $this->addNewUserLogEntry( 'autocreate' );
5064 * Load the user options either from cache, the database or an array
5066 * @param array $data Rows for the current user out of the user_properties table
5068 protected function loadOptions( $data = null ) {
5073 if ( $this->mOptionsLoaded
) {
5077 $this->mOptions
= self
::getDefaultOptions();
5079 if ( !$this->getId() ) {
5080 // For unlogged-in users, load language/variant options from request.
5081 // There's no need to do it for logged-in users: they can set preferences,
5082 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5083 // so don't override user's choice (especially when the user chooses site default).
5084 $variant = $wgContLang->getDefaultVariant();
5085 $this->mOptions
['variant'] = $variant;
5086 $this->mOptions
['language'] = $variant;
5087 $this->mOptionsLoaded
= true;
5091 // Maybe load from the object
5092 if ( !is_null( $this->mOptionOverrides
) ) {
5093 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5094 foreach ( $this->mOptionOverrides
as $key => $value ) {
5095 $this->mOptions
[$key] = $value;
5098 if ( !is_array( $data ) ) {
5099 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5100 // Load from database
5101 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5102 ?
wfGetDB( DB_MASTER
)
5103 : wfGetDB( DB_SLAVE
);
5105 $res = $dbr->select(
5107 array( 'up_property', 'up_value' ),
5108 array( 'up_user' => $this->getId() ),
5112 $this->mOptionOverrides
= array();
5114 foreach ( $res as $row ) {
5115 $data[$row->up_property
] = $row->up_value
;
5118 foreach ( $data as $property => $value ) {
5119 $this->mOptionOverrides
[$property] = $value;
5120 $this->mOptions
[$property] = $value;
5124 $this->mOptionsLoaded
= true;
5126 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
5130 * Saves the non-default options for this user, as previously set e.g. via
5131 * setOption(), in the database's "user_properties" (preferences) table.
5132 * Usually used via saveSettings().
5134 protected function saveOptions() {
5135 $this->loadOptions();
5137 // Not using getOptions(), to keep hidden preferences in database
5138 $saveOptions = $this->mOptions
;
5140 // Allow hooks to abort, for instance to save to a global profile.
5141 // Reset options to default state before saving.
5142 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5146 $userId = $this->getId();
5148 $insert_rows = array(); // all the new preference rows
5149 foreach ( $saveOptions as $key => $value ) {
5150 // Don't bother storing default values
5151 $defaultOption = self
::getDefaultOption( $key );
5152 if ( ( $defaultOption === null && $value !== false && $value !== null )
5153 ||
$value != $defaultOption
5155 $insert_rows[] = array(
5156 'up_user' => $userId,
5157 'up_property' => $key,
5158 'up_value' => $value,
5163 $dbw = wfGetDB( DB_MASTER
);
5165 $res = $dbw->select( 'user_properties',
5166 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
5168 // Find prior rows that need to be removed or updated. These rows will
5169 // all be deleted (the later so that INSERT IGNORE applies the new values).
5170 $keysDelete = array();
5171 foreach ( $res as $row ) {
5172 if ( !isset( $saveOptions[$row->up_property
] )
5173 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5175 $keysDelete[] = $row->up_property
;
5179 if ( count( $keysDelete ) ) {
5180 // Do the DELETE by PRIMARY KEY for prior rows.
5181 // In the past a very large portion of calls to this function are for setting
5182 // 'rememberpassword' for new accounts (a preference that has since been removed).
5183 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5184 // caused gap locks on [max user ID,+infinity) which caused high contention since
5185 // updates would pile up on each other as they are for higher (newer) user IDs.
5186 // It might not be necessary these days, but it shouldn't hurt either.
5187 $dbw->delete( 'user_properties',
5188 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
5190 // Insert the new preference rows
5191 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
5195 * Lazily instantiate and return a factory object for making passwords
5197 * @deprecated since 1.27, create a PasswordFactory directly instead
5198 * @return PasswordFactory
5200 public static function getPasswordFactory() {
5201 wfDeprecated( __METHOD__
, '1.27' );
5202 $ret = new PasswordFactory();
5203 $ret->init( RequestContext
::getMain()->getConfig() );
5208 * Provide an array of HTML5 attributes to put on an input element
5209 * intended for the user to enter a new password. This may include
5210 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5212 * Do *not* use this when asking the user to enter his current password!
5213 * Regardless of configuration, users may have invalid passwords for whatever
5214 * reason (e.g., they were set before requirements were tightened up).
5215 * Only use it when asking for a new password, like on account creation or
5218 * Obviously, you still need to do server-side checking.
5220 * NOTE: A combination of bugs in various browsers means that this function
5221 * actually just returns array() unconditionally at the moment. May as
5222 * well keep it around for when the browser bugs get fixed, though.
5224 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5226 * @deprecated since 1.27
5227 * @return array Array of HTML attributes suitable for feeding to
5228 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5229 * That will get confused by the boolean attribute syntax used.)
5231 public static function passwordChangeInputAttribs() {
5232 global $wgMinimalPasswordLength;
5234 if ( $wgMinimalPasswordLength == 0 ) {
5238 # Note that the pattern requirement will always be satisfied if the
5239 # input is empty, so we need required in all cases.
5241 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5242 # if e-mail confirmation is being used. Since HTML5 input validation
5243 # is b0rked anyway in some browsers, just return nothing. When it's
5244 # re-enabled, fix this code to not output required for e-mail
5246 # $ret = array( 'required' );
5249 # We can't actually do this right now, because Opera 9.6 will print out
5250 # the entered password visibly in its error message! When other
5251 # browsers add support for this attribute, or Opera fixes its support,
5252 # we can add support with a version check to avoid doing this on Opera
5253 # versions where it will be a problem. Reported to Opera as
5254 # DSK-262266, but they don't have a public bug tracker for us to follow.
5256 if ( $wgMinimalPasswordLength > 1 ) {
5257 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5258 $ret['title'] = wfMessage( 'passwordtooshort' )
5259 ->numParams( $wgMinimalPasswordLength )->text();
5267 * Return the list of user fields that should be selected to create
5268 * a new user object.
5271 public static function selectFields() {
5279 'user_email_authenticated',
5281 'user_email_token_expires',
5282 'user_registration',
5288 * Factory function for fatal permission-denied errors
5291 * @param string $permission User right required
5294 static function newFatalPermissionDeniedStatus( $permission ) {
5297 $groups = array_map(
5298 array( 'User', 'makeGroupLinkWiki' ),
5299 User
::getGroupsWithPermission( $permission )
5303 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5305 return Status
::newFatal( 'badaccess-group0' );
5310 * Get a new instance of this user that was loaded from the master via a locking read
5312 * Use this instead of the main context User when updating that user. This avoids races
5313 * where that user was loaded from a slave or even the master but without proper locks.
5315 * @return User|null Returns null if the user was not found in the DB
5318 public function getInstanceForUpdate() {
5319 if ( !$this->getId() ) {
5320 return null; // anon
5323 $user = self
::newFromId( $this->getId() );
5324 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5332 * Checks if two user objects point to the same user.
5338 public function equals( User
$user ) {
5339 return $this->getName() === $user->getName();